Sunday, May 15, 2016

Swift Tutorial - Part 6 - Tip Calculator App, UISlider, if let

Tip Calculator App, UISlider, if let

Video Description 
The purpose of this app is to get more familiar with the concept of IBAction and IBOutlet. We also introduced UISlider and how we can get the value out of it.

if let

There is an important concept in swift that is mentioned in this part of tutorial and it's nothing but "if let". Whenever you unwrap an optional, you should be very careful because if the value that you are trying to unwrap is equal nil or null, it will throws an exception and crash your app. In order to be safe while we unwrap an object, we can use if let logic like bellow:
if let variableName = someValue {
            //someValue is not nil and it's safe to unwrap
        else {
            //someValue is nil and cannot be unwrapped

In the above statement, if someValue is not nil it will go to the first bracket but if it's nill, it will go to the else statement. This concept is highly recommended for unwrapping the values that we are not sure if it's nil or not.

Source Code for the app

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var billAmountField: UITextField!
    @IBOutlet weak var tipPercentageLabel: UILabel!
    @IBOutlet weak var totalLabel: UILabel!
    @IBOutlet weak var tipAmountLabel: UILabel!
    @IBOutlet weak var tpSlider: UISlider!
    @IBAction func calculatePressed(sender: UIButton) {
    @IBAction func sliderChanged(sender: UISlider) {
        tipPercentageLabel.text! = "Tip Percentage " + String(Int(sender.value)) + "%"
    func calculateTip() {
        var tipAmount = Float()
        var total = Float()
        if let billAmount = Float(billAmountField.text!) {
            tipAmount = billAmount * tpSlider.value/100
            total = tipAmount + billAmount
        else {
            tipAmount = 0
            total = 0
        tipAmountLabel.text! = String(tipAmount)
        totalLabel.text! = String(total)


Download Tip Calculator App from here

Sunday, April 17, 2016

Swift Tutorial - Part 5 - View Lifecycle

View and Controller communications and View Lifecycle

Video Description 

View and Controller communication

In the Model View Controller design pattern we have communications between View and Controller. If Controller wants to send message to the view, it uses IBOutlet. If View wants to send message to the controller that for example some button pressed or the slider has changed it uses IBAction.

View Lifecycle

A series of methods that are sent to the View Controller when things happened. For example if we want to initialize some parameters before view appears to the user, we should use view lifecycle methods. Using these methods means overriding them. Because we override these methods, the first line of each method we should call the super (super class) and the name of the method. Here are the important view lifecycle methods:


The most important view lifecycle method is this method. This is a great place for initialization because it will be called only one time during the whole lifecycle and also all outlets are set. But do not initialize things that are related to geometry because at this point we can't be sure if we are on iPhone 5 size or 4 or iPad ...
override func viewDidLoad() {
        //Do one time initializations


This method is called each time that the view appears to the screen so it's not a good place for initialization because it could be called more than one time during the lifecycle. But it's a good place for updating the view.
override func viewWillAppear(animated: Bool) {
        //Do updating the view and geometry settings


This will be called a moment before view disappear from the screen. This is a good place to save the data to the storage. For example remembering the scroll position or saving what user typed so far, in order to retrieve it once s/he comes back to the view.
override func viewWillDisappear(animated: Bool) {

Sunday, April 3, 2016

Swift Tutorial - Part 4 - Converter App, IBOutlet, UITextField, UILabel, IBAction

Convert Miles to Feet App

Video Description 


Identifier used to identify a variable so Interface Builder can synchronize the display and connection of outlets with Xcode.
@IBOutlet weak var resultsLabel: UILabel!


is a control that displays editable text and sends an action message to a target object when the user presses the return button. You typically use this class to gather small amounts of text from the user and perform some immediate action, such as a search operation, based on that text. It has a method called "text" that returns the value that user typed.
    @IBOutlet weak var milesField: UITextField!

var textFieldValue = milesField.text!


Implements a read-only text view. You can use this class to draw one or multiple lines of static text, such as those you might use to identify other parts of your user interface. It has a method called "text" that we can set the value of the label.
@IBOutlet weak var resultsLabel: UILabel!
resultsLabel.text = "Some Value for the label";


Use this type as the return type of any action methods defined in your project. It returns nothing (void), it just a way that Xcode understands it's target action connection.
@IBAction func convertPressed(sender: UIButton) {

Source code

//  ViewController.swift
//  SConverterApp
//  Created by Hamid on 4/3/16.
//  Copyright © 2016 HuxTek. All rights reserved.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var milesField: UITextField!

    @IBOutlet weak var resultsLabel: UILabel!
    @IBAction func convertPressed(sender: UIButton) {
        // 1 mile = 5280.0 feet
        let miles = Float(milesField.text!)
        let feets = miles! * 5280.0
        resultsLabel.text = String(feets)


Download converter App from here

Sunday, February 28, 2016

Swift Tutorial - Part 3 - Playground, enum, Optional, casting

Playground, enum, Optional, cast

Video Description


Swift has a very cool feature that allows you to write a code and get a quick result at the right side of the screen. In order to make a Playground file you should open the Xcode. From the left hand side of the screen select "Get started with a playground". From the opening window add a name for your file and choose the platform you want to code (for this tutorial select iOS) and then give it a location to save. t opens a blank page that you can write your code there. In order to test the playground, copy paste the code that we wrote in previous tutorial.


There are 3 categories that we can code in Swift (class, struct and enum). One of the categories are called enum. Here is how we define enum in swift:

enum Gender {
    case Male
    case Female

Then we can use it like bellow:
var huxTek: Gender
huxTek = Gender.Male

We can alsowrite only .Male like this:
huxTek = .Male

we can have a switch for this enum like bellow:
switch huxTek {
    case .Male:
        print("A man")
    case .Female:
        print("A woman")
Optional !?

One of the important subjects that you should get familiar early in the game is optional type. You gonna see optional type in many place and actually you will use it a lot during  swift programming. That's why I dedicated a separate session just for Optional type.

Optional is just an enum with 2 cases like bellow:
enum Optional{
    case None
    case Some(T)
One case is none or null and the other case is something and something could be any type (String, Array, Int, ...). In order to explain it in an example, lets define a dictionary.
var myDict = [String:String]()
myDict = [
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
The output of the above code is:

Unwrap Optional !

The reason that we have the word Optional around the val1 is because myDict["key1"] returns an optional. It means that it could have some value or nil. In order to unwrap the optional you should put ! after the optional value like bellow:
The output of the above code is:
Optional binding

In order to assign an optional type into a variable safely we should use the following pattern:
if let key1Val = myDict["key1"] {
Imagine our dictionary includes key as String and value as String or another dictionary. The way we define it is like bellow. Since we don't know if it's String or a dictionary we just use a type called AnyObject. It means any type. 

var myDict = [String:AnyObject]()
myDict = [
    "key1": ["subKey1":"subVal1"],
    "key2": ["dasda", "asdasd"],
    "key3": "val3"
If we define a variable to get "key1" value, it returns the type as AnyObject because it doesn't know the type. In order to define a type for it we need to cast it like bellow:
    var sub1Key1Value = myDict["key1"] as! [String:String]
Now it knows that the type is a dictionary with key as String and value as String. In order to safely check if an object is a certain type we can use "is" function as bellow: 
if myDict["key1"] is [String:String] {
    var sub1Key1Value = myDict["key1"] as! [String:String]
We have learned how to unwrap optional into a type, now we need to know how to define an optional type. It's very easy, you just have to add a question mark after the type of the variable.
var myString: String?
It's very important to know that after we put question mark, the variable is no longer a String type. It's type optional that could be String. In order to print it out we need to unwap it with ! 

Sunday, February 7, 2016

Swift Tutorial - Part 2 - Swift Foundation Frameworks

Swift Foundation Frameworks

Video Description


In order to define a variable in swift we use var at the beginning of the variable then the name of the variable and at the end we define the type of the variable like bellow:
var myVariable:String = "Some String Value"


If the value of a variable doesn't change during it's life cycle, we should use let instead of var, otherwise compiler would show warning. We define a variable with let like bellow: 
var myVariable:String = "Some String Value"


In order to print on console we can use print function in swift, here is the example:
print("This text will be printed in console after running the application")


From the name of this class it's obvious that it's for defining strings. Here is an example:
var myVariable:String = "Some String Value"


let version: Double = 1.0


let myInteger: Int = 2


let isAwesome: Bool = true


We have 2 ways to define an array, here is the first one:

var letters = Array<String>()
letters = ["a", "b", "c", "d"]

The second way is to just define it like bellow:

var letters = ["a", "b", "c", "d"]

We can iterate the array objects like bellow:

var numbers = [Int]()
numbers = [1, 2, 3, 4]
for number in numbers {


We have 2 ways to define a dictionary, here is the first one:
var dict = Dictionary<String, Int>()
dict = ["One": 1, "Two":2]

The second way is to just define it like bellow:
var dict = [String:Int]()

We can iterate through keys and values of a dictionary like bellow:
for (key, value) in dict {
   print("Value for \(key) is \(value)")

NSObject, NSNumber, NSData, NSDate

These classes are inherited from Objective-c language and we will talk about them later

Saturday, January 30, 2016

Swift Tutorial - Part 1 - Hello World App

Introduction to Swift

Video Description 

Before starting Swift tutorial we should know that some tutorials that I have created for Objective-C language are valid for swift, like the first three ones that we will introduce here.

Download Xcode

Here is the link for both video and description of how we can download the Xcode ( iOS development environment)

Create Hello World App

Creating Hello World App in Swift is almost identical with Objective-C one. It has just one small difference which is choosing the language of programming. Instead of Objective-C, you should choose Swift.

Xcode components

In this tutorial I have explained each components of Xcode and even after 2 versions of iOS (8 and 9) we have similar layout for Xcode menus and button. They just changed the icons. So in order to get familiar with these components please watch this tutorial.

Sunday, November 1, 2015

iOS Tutorial - Part 35 - Popover for iPhone and iPad

Create Popover for iPhone and iPad

Video Description 
Sometimes we don't want to cover the whole view for showing another view controller. This is mostly for iPad because it has larger screen. But it's also possible to show popover on iPhone. Creating a popover is very easy, it's a type of connection between view controllers. All you have to do is to connect the button or whatever action you want to another view controller by control dragging and the choose "Present As Popover", that's it. This will show popover only for iPad but for iPhone you have to do one more step.

Popover for iPhone

iOS 8 offered an easy way to implement popover for iPhone. All you have to do is to declare UIPopoverPresentationControllerDelegate:
@interface ViewController () <UIPopoverPresentationControllerDelegate>

Then put the view controller delegate equal to self:
self.popoverTvc.popoverPresentationController.delegate = self;

And at the end implement the delegate method:
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
    return UIModalPresentationNone;

Adapt the popover size based on the content

The popover that we created so far has not a proper size. The default size is very big and unnecessary. In order to fix this issue we need to override the prefferedContentSize property of the popover view controller. In this example we have a table view and we need to get the size of the table view and show only the cells that has value (not empty cells).
if (self.tableView && self.presentingViewController) {
        self.preferredContentSize = [self.tableView sizeThatFits:self.presentingViewController.view.bounds.size];
First we chech if tableView and presentingViewController (The view controller that is presenting at that moment) is not nill. then we set the preferredContentSize equal the tableiew size that fits presentingViewController size.


Download this app here