Category Archives: iOS

Swift Programming Language – Part 1

This blog will explain some concepts of swift programming language which are as follows:-

1. Basics

2. Operators

3. String and Characters

4. Collection Types

5. Control Flow

6. Functions

All topics will be covered with example.

Basics

Swift is a new programming language for iOS and OS X application developers. Swift have same basic DataTypes as in Objective-C and C.
There is some new features which is not available in Objective-C and C as follows:-

a.) Tuples

Using Tuples a function can accept grouping of values and also return multiple values.

b.) Optional types

Its a most powerful feature of swift programming language. Optional are similar to using nil in objective-C. Its not only use with class type, can also use with any type.

Constants and Variables

The value of constants can not be changed once its initialized but the value of variable can be modify after initializing it.

How to declare a variable and constants:-
“let” keyword is use to declare a constant and “var” keyword is use to declare a variable.

Example: Below example demonstrate how to declare and initialize a constant and variable.

Step 1 Create a command line tool project.
Step 2 Open a main.swift file and code as below:

    import Foundation
    let height = 200            // Constant
    var width = 400             // Variable
   // Statement will log the output on console like NSLog in Objective-C
   println("Width = \(width) and Height = \(height)") 

Output:
      Width = 400 and Height = 200

In variable we can reassign new value like as

    import Foundation
    let height = 200         // Constant
    var width = 400          // Variable
    width = 300
    // Statement will log the output on console like NSLog in Objective-C
   println("Width = \(width) and Height = \(height)") 

Output:
      Width = 300 and Height = 200

But we can not assign new value to constant like as

    import Foundation
    let height = 200            // Constant
    var width = 400             // Variable
    height = 300
    // Statement will log the output on console like NSLog in Objective-C
   println("Width = \(width) and Height = \(height)") 

Error “Can not assign to ‘let’ value height”

we can also declare multiple variable and constant like as

var a = 2, b= 3

Note: In swift language , a statement is allow without semicolon. But semicolon is require in case of multiple statement in single line.

Type Annotations

It means specify the data type of variable at time of declaration like as:

import Foundation
var width : Int = 20
println("Width =  \(width)")

Output:
    Width = 20

Multiple variable declaration:

import Foundation
var width , height: Int
width = 20
height = 30
println("Width = \(width) and Height = \(height)") 

Output:
      width = 20 and Height = 30

Note:
a) if we declare like as in multiple variable

         var width , height: Int = 20
         It will give error such as “Type annotation missing in pattern”

b) You must initialize variable before using it.

         import Foundation
         var width : Int
         println("Width =  \(width)")

It will give error such as “Variable width used before being initialized”

Tuples

Tuples use to group multiple type of values in single compound value. Eg:

    import Foundation
    // Declare variable student of Tuple type which have two values such as name and age
    var student = ("Ram" , 25)
    var (name , age) = student
    println("Name is =  \(name) and Age is = \(age)")

Output:
Name is = Ram and Age is = 25

Optionals

Optional means variable may have a value or it may not have. It use to declare a variable with value nil.

Eg:
Program 1.

    import Foundation
    // Option name variable declaration
    var name : String?
   if name
   {
        println("Name is =  \(name)")
   }
   else
   {
        println("Name is Nil")
   }

Output:
      Name is Nil

Program 2.

    import Foundation
    // Option name variable declaration
     var name : String?
     name = "Ram"
     if name
     {
        println("Name is =  \(name)")
     }
     else
    {
        println("Name is Nil")
    }

Output:
      Name is = Ram

Operators

Operators are unary , binary and ternary.

Unary operator which apply on one operand. Binary operator which apply on two operand. Ternary operator which apply on three operand.

Assignment Operator

Assignment operator assign value of right operand to left operand.

Eg:
var x , y : Int

x = 10 y = 20

x = y // Here x contains 20
we can assign tuple as well to left side such as

var (x, y) = (10, 20) // Here x contains 10 and y contains 20

Arithmetic operators

Addition (+) , Minus (-), Multiplication (*), division (/)

Behave same as in c or in objective-c.
In swift , + operator can use to concatenate the String.

Eg:

import Foundation
// Option name variable declaration
var firstName = "Ram", secondName = "Shyam"
var fullName = firstName + secondName
println("Name \(fullName)")

Output:
    Name RamShyam

Remainder operator (%)

Remainder operator in swift can also apply on floating point remainder calculation.

Increment/Decrement Operator

Behave same as in c or in objective-c.

Compound assignment operator

Behave same as like c and objective-c language.

Eg:
var c = 2

c += 3 // Here c contain 5

Comparison Operator

Swift have all comparison operator like in c and objective-c:
Less than (<), Greater than (>) , Equal to (==), not equal to (!=) etc

Nil Coalescing Operator

The nil coalescing operator syntax is like as (a ?? b). It means if a is nil then b will be use.

Eg:

var defaultValue = “DefaultValue”
var anotherValue : String? // Initialize as nil var actualVale = anotherValue ?? defaultValue

// Here actualValue

variable contains “DefaultValue” string.
if anotherValue var is not nil then actualValue variable contain the anotherValue. Range Operator
Swift includes two range operators.
Closed Range Operator
Closed range operator syntax is (a…b). It will run from a to b.
Eg:

    import Foundation
    var a = 1, b = 2
    for value in a...b
    {
        println("Value is \(value)")
    }

Output:
      Value is 1
      Value is 2

Half-Open Range Operator
Half-Open range operator syntax is (a..<b). It will run from a and upto less than b Eg:

         import Foundation
         var a = 1, b = 2
        for value in a..<b
        {
            println("Value is \(value)")
        }
Output:
      Value is 1

Logical Operators

Logical operator is similar to logical operator in c language. Logical And (&&), Logical OR (||), Logical Not (!)

Strings and Characters

String is a collection of characters. In swift language , String data type use for string type value.

Eg:

// String type initialized
// Optional String type
// String type initialized
// Initializing empty string

if we initialize a string with “var” keyword that it means it is mutable string and if we initialize string using “let” keyword that it means immutable string.

Character can be declare and define using the Character keyword as annotation.

Eg:
var singleChar : Character = “A”

var name = “Any Name”
var name : String?
var name : String = “Any Name” var name = String()

String Concatenation
String can be combined using “+” operator like as

var firstName = “Jhon”
var scondName = “Player”
var fullName = firstName + secondName // it will contain JhonPlayer

Counting Characters

There is countElements function which we call on string to count elements.

Eg: countElements(fullName) // It will return 9

we can compare sting using comparison operator (==). And we also have function hasPrefix and hasSuffix to check prefix and suffix.

Collection Types

Swift have two collection types: Array and Dictionary. Collection type can also mutable and immutable.

Array
Array store multiple values of same type. We can declare array like as: var list : [String] = [“A”, “B”] // Its a string type array

To count number of items in an array use count function. And to check whether array is empty or not use isEmpty function.
To insert at specific index swift provide insert method.

eg:
list.insert(“Value”, atIndex:0)

we can iterate an array using for-in loop.

Dictionary

Dictionary store multiple values of same type in key value pairs.

Dictionary can be declare and define like as:

Eg:
var someDic : [String : String] = [“Key1” : “Value1”, “Key2” : “Value2”]

We perform following operation on dictionary such as

updating dictionary, count elements, check whether is empty or not.

Control Flow

There are following elements of control flow:
for, do-while, while, if, if-else, switch, break, continue so on.

Swift add for-in loop and also make switch statement powerful comparison of c language.

Loops

Some basic loop are same like in c language. Below is the example of for-in loop which is new in Swift language.

Eg:- for – in loop

    import Foundation
    var a = 1, b = 2
    for value in a...b
    {
        println("Value is \(value)")
    }

Output:
      Value is 1
      Value is 2

we can use _ if we are not going to use value like as

Eg:
for _ in a…b

{

println(“Value Blank”)

}

Switch

Switch statement is faster than if – else statements. Switch contain some matching pattern. Its syntax is:

switch someValue

{

case value1:

}

statement case value2:

statement default:

statement

In Swift language, if we don’t use break statement in case then it will not jump to next case like in C language.

Eg:

import Foundation
var a = 1, b = 2
for value in a...b
{
    switch value
{
     case 1:
        println("Value 1")
     case 2:
        println("Value 2")
     default:
       println("No Value")
}
}

Each case must have alteast one statement to execute else will give compile time error.

We can use Tuple in test cases and also can use where clause.

Fallthrough

To fall through to next case in swift language we use fallthrough keyword.

Eg:

import Foundation
var a = 1, b = 2
for value in a...b
{
    switch value
{
     case 1:
         println("Value 1")
         fallthrough;
     case 2:
         println("Value 2")
     default:
         println("No Value")
}
 }

For value = 1, two cases will execute case 1 and case 2.

Functions

Functions are block of code which perform some specific task. Function can take parameter as input and return some parameter/parameters as output.

Below is the example of function which take name as parameter and print the name. Eg:

    import Foundation
    func printName(name :String)
    {
        println(name);
    }
    printName("Jhon") 

Function returning value:
    import Foundation
    func printName(name :String) -> String
    {
        return name + "Player"      // Concatenating string
   }
   println(printName("Jhon"));

we can pass the multiple parameter using comma separation.

// Function calling

Functions with returning Tuple as parameter:

import Foundation
func printName(name :String) -> (firstName : String, lastName: String)
{
    var components: Array  = name.componentsSeparatedByString(" ")
    var firstComponent: String  = ""
    var secondComponent: String = ""
    if !components.isEmpty
    {
        firstComponent = components[0];
        secondComponent = components[1];
    }
    return (firstComponent, secondComponent)
}
var name = printName("Jhon Player");
println("First Name is \(name.firstName) and Last Name is \(name.lastName)"); 

Function with In-Out Parameter:

If you want to modify parameter value and preserved that modification after function exit then we supply parameter as In-Out parameter.

Eg:

import Foundation
func swap(inout a: Int, inout b: Int)
{
    var temp = a 
    a = b
    b = temp 
}
var a = 10, b = 20
swap(&a,&b)
println("A = \(a), B = \(b)")

Output:
      A = 20 , B = 10


Written By: Yogesh Arora, Software Engineer, Mindfire Solutions
Advertisements
%d bloggers like this: