TagSwift Tutorial

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”
 

Swift – Datatypes

 

As per apple documentation, Swift types can be classified into two, namely,

Each of these types are explained below in detail.

Named types

Named types, as the name implies are types with variable names. The named types can be both Swift standard library types and user defined types. It includes the following,

We will be covering primitive types and optional types in this page and the rest in their respective pages to which they are linked.

Primitive Types

In all programming languages, we have some basic types that available part of the language. In swift, we have these types availed through the Swift standard library. These include the types for numbers, characters and strings. The following table covers all the primitive types.

6UInt
Represents an unsigned integer. Internally Int refers to UInt32 in 32 bit platform and UInt64 in 64 bit platform.12Double
Represents 64 bit floating point number.

Primitive Types
SNo. Type and use
1 Int
Represents an integer. Internally Int refers to Int32 in 32 bit platform and Int64 in 64 bit platform.
2 Int64
Represents 64 bit integer.
3 Int32
Represents 32 bit integer.
4 Int16
Represents to 16 bit integer.
5 Int8
Represents to 8 bit integer.
7 UInt64
Represents 64 bit unsigned integer.
8 UInt32
Represents 32 bit unsigned integer.
9 UInt16
Represents 16 bit unsigned integer.
10 UInt8
Represents 8 bit unsigned integer.
11 Float
Represents 32 bit floating point number.
13 Bool
Represents a boolean and has two states true and false.
14 Character
Represents a single character. It accepts unicode characters.
15 String
Represents strings which is actually a collection of type Character.

Some examples are given below for the above types.

var myInteger:Int = -100
println("myInteger: \(myInteger)")

var myUnsigedInteger:UInt = 100
println("myUnsigedInteger: \(myUnsigedInteger)")

var myFloat:Float = 98.95
println("myFloat: \(myFloat)")

var myDouble:Double = 88.85
println("myDouble: \(myDouble)")

var myBoolean:Bool = true;
println("myBoolean: \(myBoolean)")

var testChar:Character = "T";
println("testChar: \(testChar)")

var testString:String = "Eezy Tutorials";
println("testString: \(testString)")

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

myInteger: -100
myUnsigedInteger: 100
myFloat: 98.9499969482422
myDouble: 88.85
myBoolean: true
testChar: T
testString: Eezy Tutorials

Note on Primitive datatypes

Quick Facts !!!

Primitive datatypes in Swift are created using structures and hence you cannot convert C types to Swift primitive types. Instead, you can use some equivalent types.

Optional Type

The primitive types are formed with the help of structures. The variables that refer to these primitive types can either contain value or no value. In order to set no value state, we should use the optional type. Optional type is formed by adding a question mark(?) to the primitive type. This optional type accepts nil for no value state. Example for optional type is given below.

var myOptionalInteger:Int?
println("myOptionalInteger: \(myOptionalInteger)")

myOptionalInteger = 10;
println("myOptionalInteger: \(myOptionalInteger)")

var myOptionalFloat:Float?
println("myOptionalFloat: \(myOptionalFloat)")

myOptionalFloat = 10.536;
println("myOptionalFloat: \(myOptionalFloat)")

var myOptionalString:String?
println("myOptionalString: \(myOptionalString)")

myOptionalString = "Eezy Tutorials";
println("myOptionalString: \(myOptionalString)")

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

myOptionalInteger: nil
myOptionalInteger: 10
myOptionalFloat: nil
myOptionalFloat: 10.53600025177
myOptionalString: nil
myOptionalString: Eezy Tutorials

Quick Note to Objective C developers

Remember !!!

The nil used in Objective-C is not equivalent to the nil used in Swift. nil is a pointer to non existing object in Objective-C and in Swift used for non existent value including primitive types with the help of optionals.

Compound types

Compound types is type without name that can contain named and compound types. It includes,

Use the respective links to know more with relevant examples.

 

Swift – Lexical Structure

 

In this section, we will see the variable valid tokens that forms the basic structure of the swift program also called the lexical structure. The valid tokens include,

Comments

Comments are those statements intended to add some additional information to fellow developers. These statements are ignored and skipped by the compiler. We have two types of comments namely single line comments and multiline (or block) comments as shown below in example.

// Single line comment 
/* Multi line (or block) comment - can use
multiple lines */

Whitespace

Whitespace is used to separate different tokens and also add readability to code. Whitespace characters for readability especially used in binary operations are ignored and skipped by the compiler. An example shown below in example.

var a = 19 
var sum = a + 20

You can find whitespace characters found in the above example. The space between var and a are mandatory as they are two different tokens. But the space between a and =, and the space between = and 19 are just for readability. Similar whitespace characters are used in sum = a + 20 only for readability.

Identifiers

Identifiers can contain alphabets, numbers and combining unicode characters. Identifiers can begin with an upper case or lower case letter A through Z, an underscore (_), a noncombining alphanumeric unicode character in the basic multilingual plane, or a character outside the basic multilingual plane that isn’t in a private use area as per apple swift language guide. Due to support of unicode characters, its now possible to name variables in your native languages across the world.

As in all programming languages, you cannot use keywords for identifiers. But, if you still want to use it, keyword can be used by adding a backtick(`) before and after it. But x and `x` are not different. Examples of valid identifiers are shown in following example.

_variable `class` name number123 
变量 भेरिएबल متغير variável পরিবর্তনশীল
переменная 変数

Keywords

The list of keywords in swift are listed below.

class deinit enum
extension func import
init let protocol
static struct subscript
typealias var break
continue default do
else fallthrough if
in for return
switch where while
as dynamicType is
new super self
Self Type __COLUMN__
__FILE__ __FUNCTION__ __LINE__
associativity didSet get
infix inout left
mutating none nonmutating
override precedence prefix
right set unowned
unowned(safe) unowned(unsafe) weak
willSet

Literals

Literals can be any three of the following.

  • Integer literals
  • Floating point literals
  • String literals

These are nothing but values we assign to variables. Examples of the above literals are given below.

// Integer literal 10
var a = 10
// Floating point literal 10.4
var b = 10.4
var c = "Hello"

Integer Literals

Integer literal can be represented in decimal, binary, octal and hexadecimal forms. An example for representing a integer decimal number 20 in different forms is shown below.

//Decimal integer literal 20
var a = 10
//Binary integer literal 20
var b = 00010100b
//Hexadecimal integer literal 20
var c = 14x
//Octal integer literal 20
var d = 24o

One of the new features available in swift is that you can use underscore(_) between digits for readability as shown below. Similarly, leading zeros will be ignored by compiler.

var a = 100_000_000

Floating point Literals

Floating point numbers can be simple decimal numbers, exponential numbers both decimal and hexadecimal floating point numbers. An simple example is shown below.

//Simple floating point number
var a = 10.5
//Exponent floating point number for 1050
var b = 10.5e2
//Exponent floating point number for 0.1050
var c = 10.5e-2
//Hexa decimal exponent floating point number for 40
var d = 0xAp2
//Hexa decimal exponent floating point number for 2.5
var d = 0xAp-2

String Literals

String literals are characters are enclosed within double quotes. Strings can contain escape sequences to represent characters like qoutes. Example for string literal is shown below.

var a = "test"
var a = "Hello\nWorld"

Escape sequences

Character Use
\0 Null Character
\\ Backslash
\t Horizontal Tab
\n New line
\r Carriage Return
\” Double Quote
\’ Single Quote

Operators

There are different operators supported in swift which includes + ,- ,* , /, %, ^, &, &&,| , ||, ++, –, ~, < ,> ,. ,-> ,!. The list of operators are explained in swift- operators tutorial.

 

Swift – First Program

To get started with Swift, download the latest Xcode 6 version.

Once you have completed installation of Xcode 6, Follow the steps to create a command line application.

  1. Open Xcode.
  2. Select File -> New -> Project.
  3. In the new window that appears, Select Applications under OS X.
  4. Select command line application and press Next.
  5. Enter “Product Name” and press Next.
  6. Select location to save for your new project.

Now, you will find a main.swift file created for you. It contains a Hello World example by default as shown below.

import Foundation

println("Hello, World!")

When we run the above program, we will get the following result in the debug console.

Hello, World!

The println is used print any statement in a new line. As you can see, you don’t need a semi colon to terminate the statement. Use NSLog function, if you want to log in a special formatted log with time and application name.

Note to Objective-C developers

Remember !!!

Unlike NSLog, println don’t add the time during which the log statement was executed. For strings including the one used in NSLog(“string”), never use @ symbol as in Objective-C.

 

Swift Programming Language

 

Apple has been evolving iOS/ Mac programming day by day and the latest addition is an all new programming language, Swift. There has been a mixed bag of reactions on the new language with some Objective-C lovers wishing to stay away from swift and others find it prospective for the future. As we all know, iOS/Mac programmers have to shift to swift one day or the other.

Pros using Swift

  • Better memory management and type safety.
  • Multiple return values with tuples.
  • Better performance.
  • Mix and match approach helps to retain and use existing Objective -C code.
  • Easier to learn swift for programmers in other languages.

Cons using Swift

  • Difficult to convert existing projects completely to swift.
  • Existing developers need to spend extra time creating projects using swift.
  • No clear information on when Objective-C support will be dropped.
  • Arrays are type dependent unlike NSArray that can add any type of objects.

In this section of our website, we try to provide a great start point for learning swift step by step with lots of code samples. Most of the pages will have a note for the Objective-C developers to help them make a easier transition to Swift programming language. New programmers who don’t have knowledge of Objective – C can ignore these notes. Enjoy learning!!!