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) {
        calculateTip()
    }
    
    @IBAction func sliderChanged(sender: UISlider) {
        tipPercentageLabel.text! = "Tip Percentage " + String(Int(sender.value)) + "%"
        calculateTip()
    }
    
    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

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:

viewDidLoad

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() {
        super.viewDidLoad()
        //Do one time initializations
    }

viewWillAppear

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) {
        super.viewWillAppear(animated)
        //Do updating the view and geometry settings
    }

viewWillDisappear

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) {
        super.viewWillAppear(animated)
        
    }

Sunday, April 3, 2016

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

Convert Miles to Feet App



Video Description 

IBOutlet

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

UITextField


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!

UILabel

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";

IBAction

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

Download converter App from here

Sunday, February 28, 2016

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

Playground, enum, Optional, cast


Video Description

Playground

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.

enum

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"
]
print(myDict["key1"])
The output of the above code is:
"Optional("val1")\n"

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:
print(myDict["key1"]!)
The output of the above code is:
"val1"\n
Optional binding

In order to assign an optional type into a variable safely we should use the following pattern:
if let key1Val = myDict["key1"] {
    print(key1Val)
}
Cast
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]
    print(sub1Key1Value["subKey1"]!)
}
?
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

var

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"

let

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"

print

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")

String

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"

Double

let version: Double = 1.0
print(version)

Int

let myInteger: Int = 2
print(myInteger)

Bool

let isAwesome: Bool = true
print(isAwesome)

Array

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


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

The second way is to just define it like bellow:



var letters = ["a", "b", "c", "d"]
print(letters[2])

We can iterate the array objects like bellow:


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

Dictionary

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)

http://huxtek.blogspot.com/2013/12/fist-post.html

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.

http://huxtek.blogspot.com/2013/12/creating-hello-world-app-for-iphone-ipad.html

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.

http://huxtek.blogspot.com/2013/12/description-of-xcode-components.html