TagiOS 8

Swift for loop statement

Simple for statement

A simple for statement consists of an initializer, condition and an increment/decrement. In the following example, we have an variable i initialized to 0 and we check for a condition i<2 and use an increment i++. This i++ could be i+1 or i-2 and so on. It depends on your need.

for(var i = 0; i<2; i++){
    println(i)
}

Output

0
1

for in with dictionaries

We can access an key value of dictionaries with for in statement. A simple example is shown below.

var dict = ["1":"Eezy", "2":"Tutorials"]
for (key,value) in dict
{
    println("\(key) : \(value)")
}

Output

2 : Tutorials
1 : Eezy

for in with arrays

We can access an array of values with for in statement. A simple example is shown below.

var array = ["Eezy", "Tutorials"]
for value in array
{
    println(value)
}

Output

Eezy
Tutorials

for in with ranges

Ranges provides more power to for. You can just specify the starting and finishing values of a range. A simple example is given below. The range includes the starting and ending number

for i in 0...3
{
    println(i)
}

Output

0
1
2
3

 

Swift if statement

 

A simple example is shown below. As the name implies the block of statement for if executes if the condition is satisfied.

let a = 20
if a == 20 {
println("\(a)")
}

Output

20

if else example

A simple if else example is shown below.

let a = 10
if a == 20 {
println("\(a)")
}
else{
println("Not 20")
}

Output

Not 20

if else ladder example

let a = 3
if a == 1 {
println("Number is 1")
}
else if a == 2 {
println("Number is 2")
}
else if a == 3 {
println("Number is 3")
}
else{
println("UnKnown number")
}

Output

Number is 3

Optionals and if statement

var name: String?
if let tempName = name {
    println("value present")
}
else {
    println("NIL")
}

Output

NIL

You can see that optionals can be checked with if let syntax. Also, it copies the variable locally and helps us not making changes to the original value.

Swift – Switch cases

 

Firstly, in Swift, you no longer need to add break statement like other conventional programming languages like C. The other use of break was that if you don’t call break, it will automatically execute other cases too. For this purpose, we have fallthrough method that makes the next cases to be executed even if the current case succeeds. Let us now look at some examples.

Simple Switch case example

let a = 10
switch (a){
case 1:
println("Hello")
case 10:
println("World")
default:
println("Nothing")
}

Output

World

Another important thing to note is that, cases should be exhaustive and hence we should add a default case to make it exhaustive. The default case should have at least one statement. The one statement could be even break if you don’t need to do any other stuff.

Switch Ranges example

let a = 4
switch (a){
case 1...10:
println("Hello")
default:
break
}

Output

Hello

In the above example refers to range 1 to 10 with both 1 and 10 included.

Switch with fallthrough example

let a = 4
switch (a){
case 1...10:
println("One to ten")
fallthrough
case 5...10:
println("five to ten")
default:
break
}

Output

One to ten
five to ten

As you can see in the above example, fallthrough enable all the subsequent cases to be executed. You may need to use break in case you want to break in one of the cases while using fallthrough.

Simple tuples example

let a = ("raj", 10)
switch (a){
case ("raj",10):
println("Raj")
case ("john",20):
println("John")
default:
break
}

Output

Raj

Tuples enables us to pass multiple values and it is supported in switch case as well. In the above example, we have used a simple string and number comparison.
 

Swift – function-type

 

Swift function type makes the function to be a first class citizen. You can pass function like objects to any other function like parameters or return values.

Every function has a function type. This function type consists of the parameters and return values. A simple example for function type is shown below.

func add(number1:Int, number2:Int)->Int{
return number1 + number2
}
let myAddFunction = add
println(myAddFunction(1,2))

When you run the above program, we will get the following output.

3

 

Swift – Dictionary

 

Dictionary in swift are used to key value pairs of some data type. The syntax for dictionary in swift is as shown below.

var (or let for constant) myFirstDictionary = [Key:value.. Key:Value]

Some example dictionaries are shown below.

var myFirstDictionary = [:]
println("myFirstDictionary:\(myFirstDictionary)")
var mySecondDictionary = ["Key1":"Value1","Key2":"Value2"]
println("mySecondDictionary:\(mySecondDictionary)")
var myThirdDictionary:Dictionary = ["Key1":"Value1","Key2":"Value2"]
println("myThirdDictionary:\(myThirdDictionary)")
var myOptionalFourthDictionary:Array?
println("myOptionalFourthDictionary:\(myOptionalFourthDictionary)")

When you run the above program, we will get the following output.

myFirstDictionary:{
}
mySecondDictionary:[Key2: Value2, Key1: Value1]
myThirdDictionary:[Key2: Value2, Key1: Value1]
myOptionalFourthDictionary:nil

Adding Values to an Dictionary

In array, adding values is made easy with the use simple hashing structure. An example is shown below

var myDictionary:Dictionary = [:]
myDictionary["Key1"] = "New Value 1"
println("myDictionary:\(myDictionary)")

When you run the above program, we will get the following output.

myDictionary:[Key1: New Value 1]

 

Swift – Arrays

 

Arrays in swift are used to store values of same data type. The syntax for arrays in swift is as shown below.

var (or let for constant) myFirstArray = [values]

Some example arrays are shown below.

var myFirstArray = []
println("myFirstArray:\(myFirstArray)")
var mySecondArray = ["Value1","Value2"]
println("mySecondArray:\(mySecondArray)")
var myThirdArray:Array = ["Value1","Value2"]
println("myThirdArray:\(myThirdArray)")
var myOptionalFourthArray:Array?
println("myOptionalFourthArray:\(myOptionalFourthArray)")

When you run the above program, we will get the following output.

myFirstArray:(
)
mySecondArray:[Value1, Value2]
myThirdArray:[Value1, Value2]
myOptionalFourthArray:nil

Adding Values to an array

In array, adding values is made easy with the use of += operator overloading. You also have append method and insert methods for inserting to array. An example is shown below

var myArray:Array = []
myArray += ["New Value 1"]
myArray += ["New Value 2"]
println("myArray:\(myArray)")

When you run the above program, we will get the following output.

myArray:[New Value 1, New Value 2, New Value 4, New Value 3]

 

Swift – Structures

 

Structures is used to represent a collection of different types. In swift, it is possible to have initializers and methods like classes. The most common difference is that class instance is passed as reference and structure is passed as copy.
Syntax

struct structureName{
   //variables and methods
}
// Structure initialization
let variableName = structureName(variable1:initialValue1,...,variablen:initialValuen)

Example

struct Student{
var name:String
var rollNo:String
func desc()->String{
return "The name of student with roll number\(rollNo) is \(name)"
}
}

 

Swift – Class

 
Class is something that acts as  a template to represent object properties and behaviour. For example, let us consider a real world object car. This object may contain properties like color, speed, model name and so on. It may have behaviours like accelerate, brake and so on.
Syntax

class className:SuperClass,ConformingProtocol1,..ConformingProtocoln{
   //variables and methods
}

Example

class Car:Vehicle,DrivingProtocol{
var turbo:String
func addTurbo(){
//Add turbo
}
}

 

Swift – Protocols

 

Protocols provides ability for us to define properties and methods that a task should conform to. For example, let us consider we have a Driving protocol. It may have methods and properties like brake and speed that conforming Car class should implement.

Syntax

protocol protocolName{
//methods and properties
}

Example

protocol DrivingProtocol{
var speed: Int { get }
func brake()
}
//Implemetation of protocol in class car
class Car:Vehicle,DrivingProtocol{
   func brake(){
      //Add brake actions
   }
}

Objective C Compatible Protocol Syntax

@objc protocol protocolName{
//methods and properties
optional
//optional methods
}

Example

@objc protocol DrivingProtocol{
var speed: Int { get }
   optional
   func brake()
}
//Implemetation of protocol in class car
class Car:Vehicle,DrivingProtocol{
   //Optional to add brake function
}

Tuples in Swift for multiple return values

 

Tuples are a great addition to Swift. It provides the ability for functions to return multiple values. In Objective-C and other languages, we need to use either custom objects or array of objects to return multiple values. Tuples helps us overcome this.

Syntax

func functionName(parameters with types)->(return values with types)

Example

func mathOperations(number1:Int ,number2:Int)->(add:Int ,sub:Int, mul:Int, div:Int )
{
return (number1+number2, number1-number2, number1*number2, number1/number2)
}

Calling a function

var a:(Int ,Int, Int, Int ) = mathOperations(1,number2: 2)
println("\(a.0)\(a.1)\(a.2)\(a.3)") 

Output

3 -1 2 0

Adding Bridging- Header – Swift

We often get the requirement of using Objective-C classes and libraries in Swift. In order to help us do this, there is something called the bridging header. The way to implement this to create a header file named project_name-Bridging-Header.h. Make sure to add this in the same folder where the project.xcodeproj file resides. I have encountered issues placing it in a different folder.

Also, you may need to add it to build setting as shown below.

Swift-Bridging-Header

Swift-Bridging-Header

Now, import the required Objective-C header files to project_name-Bridging-Header.h.
Let assume, you have a Objective-C class as shown below.

You can use the methods as shown below.

Using class methods of Objective-C in swift
 

Enumeration – enum in Swift



We often use enumeration to switch between multiple values. Following is the syntax for creating a enumeration in swift.

enum yourEnumerationName : TypeName {
    case Enum1
    case Enum2

The following shows an example how to access a enumeration of activity indicator in swift

var activityIndicator:UIActivityIndicatorView  = UIActivityIndicatorView(activityIndicatorStyle:
            UIActivityIndicatorViewStyle.WhiteLarge)
activityIndicator.startAnimating()

The declaration of UIActivityIndicatorViewStyle is as shown below.

enum UIActivityIndicatorViewStyle : Int {
    case WhiteLarge
    case White
    case Gray
}

 

Type casting in Swift

We may often need to typecast variables in swift. A simple example for type casting is shown below.

Lets assume we need to access application delegate. This can be done as shown below.

var appDelegate:AppDelegate = UIApplication().delegate as AppDelegate;

As you can see the syntax for type casting is

var varName:ClassName = yourNewObject as ClassName;

 

Properties in Swift



In swift, we can actually access all the global variables and there is not concept of data hiding.
But you may often encounter some issues in setting the global objects’ property when you decare them as optional(var myView:UIView?). The question mark(?) makes it optional allowing to accept nil values. The solution is use ! ?????
Let assume, you have a declared a variable named as shown below.

class myClass{
var myView:UIView?
}

Lets assume you have function setView. To set the value, you need to do as shown in the following.

class myClass{
   var myView:UIView?
   func setView(){
        myView = UIView(frame: self.view.frame)
        myView!.backgroundColor = UIColor.clearColor()
   }
}

If you don’t use !, you may get compiler error “Cannot assign to the result of this expression error”