Friday, 8 August 2014

An Introduction to Swift

             In the Apple World Wide Developer Conference - 2014 held on June 2nd 2014, Apple has introduced a new language named 'Swift' to be continued in the development of Mac os x and iOS technologies. Swift is designed with the scripting language-like syntax(javascript, python), Which allows the new developers to understand the language very quickly. With these introduction let's get into topic 'Introduction to Swift'.

Variable/Constant Declaration:

                    In swift the basic data types are just like other programming languages as follows.
  • Int:  Swift provides a different way to declare data types. For Int the typical declaration is as follows...
           
variable: 'var' is the keyword used to declare a variable
  • var firstInteger : Int // declaring an Int variable
                     // here 'var' is the keyword denoting variable declaration
                     // 'firstInteger' is the variable-name
                     // ':' colon always specifies a data type is going to be followed
                     // 'Int' is the keyword denoting 'Integer' type
  • var secondInteger: Int = 12 // declaring and initialising an Int variable
This  syntax is common for other primitive data types Float, Double, String and AnyObject also.
Note: AnyObject is a data type which is used to store heterogeneous data type. And also observe that, no line has the delimiter semicolon (;) in Swift. However, we have to semicolon(;), if we use multiple statements in a line

constant: 'let' is the keyword used to declare a constant.
let firstInteger : Int = 12 // declaring a constant
Similar to variables, this syntax is common for the rest of the data types as well.
Note: Constants must be initialised while declaring the identifier.

NextStep Heritage:
             NextStep is also written on top of the Objective-C library. Now in Swift these NextStep objects are also interpolated on top of the Swift library. So similar to the above data types, NSString, NSArray, NSDictionary objects also available in Swift. This is something interpolating the features of the Swift into a high extension. Those NextStep objects declaration are...
var newString : NSString 
newString = "This string will be assigned to a NSString object" 
(or)
var newString : NSString = "This string will be assigned to a NSString object"
var newUrl : NSURL
newUrl = NSURL(string:"https://www.google.co.in")
(or)
var newUrl: NSURL = NSURL(string:"https://www.google.co.in") 
Note: Here 'string' is keyword, denoting that NSURL init() called with a string.
var newData : NSData
newData = NSData()
(or)
var newData : NSData = NSData() 
 Similarly you can declare/use different NextStep objects in Swift as well.     

Type Inference:

        Type inference is one of the special primary feature of Swift, which is used to infer the data type based on the initialisation value. Consider the below example....
var firstString = "This is my first string"
  Here, the variable firstString have not been specified by any data types explicitly. But what happens is when we initialise a variable with the string value, the swift library automatically choose the variable of type String. This particular feature is called 'Type Inference' in Swift.
Similarly....
var firstInt = 24
type inferred as Int for variable firstInt. This is available for other data types(NSString, NSURL, NSData....).
var newData = NSData() // inferred to NSData type
var newUrl = NSURL(string:"https://www.google.co.in") // inferred to NSURL type
Similarly, NSRequest, NSConnection.... and so on.
Note: Here we're not explicitly specifying the object/variable belongs to particular type. But we just call the init() method of the corresponding data types get called, and the variable/object simulated with the corresponding type class. All the actions performed implicitly.
Optional Values:
                              Optional values in Swift are designed to fulfil the behaviour object-returns-nil-when-non-exist situation which is already exists in ObjectiveC. The major drawback in ObjectiveC is most of the objects are "optional", which is not good for a feasible programming. So, overcoming this issue as well as to fulfil the required behaviour 'Optional Values' are introduced in Swift. Optional values can be used only when the object-returns-nil-when-non-exist behaviour required. Otherwise "required"(normal variables/constants in Swift) values are used. Optional values are identified by normal data types suffixed with a (?) question mark. Consider the below line....
var myOptionalInt : Int?
Here a variable of type "Optional Int" has been declared. Find the (?) question mark suffixed with the Int data type, this classifies the "required"(normal) and "optional" variables. Similarly "Optional" values can also be created for other data types.

Implicit optional declaration:
var sampleString = "123"
var sampleInt = sampleString.toInt() 
Here, first variable is inferred to be of type String, second variable inferred to be Int?(optional) variable. Since the toInt() returns an Int?(optional) variable. So, the variable sampleInt is implicitly converted into optional(Int?) variable.

Optional binding:
                            Optional values can be checked with if/while condition, if it does have a value then inside the if/while block the optional values can be manipulated. Have a look at the below code....
var sampleString : String? = "hello"
if sampleString {
                        println("This optional variable has a value");
                        // statements to manipulate the optional value as we want.
           }
          else {
                        println("This optional variable doesn't have a value");
           }
     This is the so called behaviour object-returns-nil-when-not-exists, which is available in most of the ObjectiveC objects by default.

Types of optional values:
                                       There are two types in optional values, classified by '?' and '!' suffixes. The representations are as follows...

Normal optional value:
var normalOptional : String?
Implicitly unwrapped optional value:
var specialOptional : String!
         Both are having the "optional" behaviour, but the difference is the 'Implicitly unwrapped optional' can also be used as a normal(non-optional) value.

Unwrapping optional values:

                 If an optional class containing properties, then the unwrapping to access that property should contain the following keys.

             optionalClass?.property
       
Please find the '?' and '.' operators used in the above line. Here, the optionalClass is an optional value, containing a property/data-member named property. An optional class containing a property/data-member, if we want to access the property/data-member of that optional class should use the above unwrapping technique.

           var index : NSIndexPath?

         Now, the variable index is belongs to optional value(class) NSIndexPath. Where the class NSIndexPath contains a property called 'row'. So, to unwrap the value 'row' from the class 'NSIndexPath?', should follow the above signature.

         var rowValue = index?.row

Assume that the NSIndexPath? class has the skeleton like...

 class NSIndexPath?{
  //other data members...
 var row : Int
}

For instance, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list by default tableview delegate methods.  The row value exists when the cellForRowAtIndex is get called. There, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list.
So, the unwrapping of 'row' value from 'indexPath' is as follows.    

           var rowValue = indexPath?.row // variable rowValue inferred as optional Int value
           or
           var rowValue = indexPath!.row// variable rowValue inferred as normal Int value

Note: When using the '!' unwrapping, have to be very sure that the particular class exists(contains value).

Data Structures/ Collections :

                                               Similar to ObjectiveC two collections Arrays and Dictionaries are used in Swift. In iOS the Arrays and Dictionaries are just enough to achieve any kind of Collections like Stack, Queue, Dequeue, List, Map, HashMap, Set....

Arrays:

            Unlike other languages  Arrays are very powerful data structure / collection in iOS. The major drawback of Arrays in other languages are
1. Interpolation
2. Auto adjust on removal of an object

These two things are handled in Swift / Objective-C Arrays so elegantly.
           The major difference between Arrays in Swift and Objective-C is, in Objective-C Arrays are heterogeneous by default. Whereas, in Swift Arrays are homogeneous by default. However we can create heterogenous array as we want. So, by default Arrays are homogeneous, it's important to declare the array-type either explicitly or implicitly.


Explicit declaration :
(mutable)
      var firstArray : Array<Int> // explicitly declare
      var firstArray1: Array<String>

      var secondArray : Array = Int[](count:20, repeatedValue:0) // explicitly declaration and initialisation
      var secondArray1 : Array = String[](count:20, repeatedValue:0)
   
(immutable)
      let firstArray : Array<Int> = [ 1, 2]  // immutable array must be initialised
Implicit declaration :

      var thirdArray = [0]           // implicit declaration
      var thirdArray1 = ["hello"]

Array functions:
   Add an element at the last position:
      thirdArray.append(1) // appending an Int value to the array of type Int
      thirdArray.append(2)
      thirdArray1.append("welcome") // appending an String value to the array of type String
      append() function is not applicable for immutable arrays.

  Update an element at available index:
     thirdArray[0] = -1
     thirdArray1[1] = "world"

Note: An added feature to enrich the usage of Arrays is even the immutable arrays can be updated by their index. This is not available in Objective-C Arrays.
However in Swift this feature is only available in Arrays not available in Dictionaries.

            As mentioned early Swift objects are type safe, So the incompatibility or inappropriate types are identified so early, This will leads to type safe feature added to the language.  Arrays is not an exception from this default Swift behaviour.

   Add a subArray :
           thirdArray += [1,2,3,4]
           thirdArray += ["hello","hello","hello"]

     Now the new Arrays are
            thirdArray[-1,2,1,2,3,4] ,
            thirdArray1["welcome","world","hello","hello","hello"]

In some cases, heterogeneous arrays are more appropriate than the default Arrays.
Heterogeneous Array :
     
       var myArray : Array<AnyObject> = []
       myArray.append(1)

       myArray.append("hello")

Here, myArray is a heterogeneous array containing Int,String.... elements.

Dictionaries:

                    Swift dictionaries also type safe, So it's very important to specify the type when declaring implicitly/ explicitly.

Explicit Declaration :

      var myDictionary : Dictionary<Int,Int> = [ : ] // Explicit declaration with initialisation

      Here the key/value pair is specified in the format <Int,Int> explicitly. And the variable myDictionary initialised with empty Dictionary.

Implicit Declaration:

     var myDictionary1  = [ 1: "One" ]  //Dictionary type inferred as <Int,String> implicitly

     Here the variable myDictionary1 is initialised with the a Dictionary of type <Int, String>, So the myDictionary1 is inferred to have the format <Int, String>.

Heterogeneous Array inside Dictionary :

            Most often we're expected to feed a table of data into a collection. In such situations, we can use the combination of Array and Dictionary to hold the data as it is the usually done in iOS. In Objective-C Array is heterogeneous by default,  Whereas, Swift is Homogeneous by default. So we need to specify a heterogenous Array inside Dictionary as follows.

    var myDictionary3 : Dictionary<Int,Array<AnyObject>> = [:]
    myDictionary3[1] = ["name" , 25, "M"]
    myDictionary3[2] = ["name2" , 25, "F"]

    Here the Dictionary is composed of an Int (predominantly used for  primary key in table ) : a heterogeneous Array (combination of String, Int) as a Tuple. Now the data are organised in the variable myDictionary3 in the following format.
   [
    1: ["name", 25, "M"],
    2: ["name2", 25, "F"]
   ]
Similarly, we can use nested Dictionary based on the requirements.


Functions :


                   Functions in Swift are having a unique syntax comparing with other languages. Which is very easy to understand

func function-name (param1 : param-type, param2 : param-type, ....) -> (return-type(s)) {

// function definition goes here...
}

             Here, the func is the keyword specifying that subsequent block is belongs to a function. Then the function-name is the identifier for the function, then parameters list, then -> key specifies that this function has the return-type(s) proceeding next to it.  If the function return type is void, we need not to specify the -> Void.

Variadic parameters: 
                                   Variadic parameters are continuous homogeneous elements that are used as a temporary array structure. Variadic parameters used only in the function call, they are identified by the ... symbol after the param-type specification. For example...

func sumOfNumbers ( a : Int...)->Int{
var sum = 0;
for num in a{
    sum +=num
}
return sum
}

var nSum = sumOfNumbers(20,50,60,70)

  Here the in the function sumOfNumbers parameter a  is variadic, since the data-type is followed by ... symbol. This is how the variadic parameters are used as a temporary array.

Note: There should be only one variadic parameter can be used in a function, If a function containing many parameters type, then the variadic parameters must be specified at  the end.


External/Internal Parameters:
                                 If the parameter list in function call is big, It's better use external parameters to identify each parameter uniquely. Consider the below snippet 


func firstFunction ( a : Int , b : Int, c : Int...) -> (Int) {
    var sum = 0
    for num in b{
        sum += num
    }
    return sum+a
}

var total = firstFunction( 20, 50, 60, 70, 40, 25, 35 );

Here in the function call the parameters 20, 50, 60, 70 are passed. The compiler starts from left side, each parameter is assigned to non-variadic parameters, once the non-variadic parameters is get assigned remaining parameters are assigned to variadic parameter which is specified at the last always. This is how the compiler understands the above snippet. In some cases if we may have to identify the non-variadic parameter and variadic parameter list to avoid ambiguity. In that cases it's better to use external parameters. Consider the below snippet which has the external parameters applied.


func firstFunction ( A a : Int , B b : Int, C c : Int...) -> (Int) {
    var sum = 0
    for num in c{
        sum += num
    }
    return sum+a+b
}

var total = firstFunction( A : 20, B : 50, C : 60, 70, 40, 25, 35 );

Here in the above statement an additional naming-field is added in each parameters. For our understanding we are naming each parameter as above. In the function firstFunction(), each parameter has two fields. They are...
1. The first one is external parameter ( passed by us )
2. The second parameter is internal parameter ( identifier to the particular variable ).
However, only internal parameters are used in manipulating each parameters. So the purpose of the external parameter is identify each parameters in the function-call uniquely. 

Now the non-variadic parameters and variadic parameter are identified easily with the help of external parameters.

Protocol : 

               Protocols are set of properties and functions that are simulated by any classes, structures, enums. This feature is already exists in Objective-C, Swift retains it with the same functionalities.

Note: While inheriting protocols, all the data members(properties and functions) has to be overridden. This activity is called "conforming to the protocol".

creating a protocol
protocol protocol-name {

// data members go here...

}

Inheriting a protocol in a class

class class-name : protocol-name
{
     //conforming to protocol goes here...
}

similarly with a struct

struct struct-name : protocol-name
{
      //conforming to protocol goes here...
}

Have a look at the following protocol implementation....

               protocol Area {
    
                          var a : Int { get }
                          var b : Int { get }    
                          func findArea () -> Int

               }

            class Square : Area {    
                       var A = 10;
    
                       var a : Int {
                           return A;
                        }
    
                        var b : Int {
                            return A;
                        }
    
                        func findArea() -> Int {
                            return a*b;
                       }
                 }


                 class Rectangle : Area {    
                        var A = 10, B = 20;
    
                         var a : Int {
                               return A;
                          }
    
                         var b : Int {
                              return B;
                          }
    
                          func findArea() -> Int {
                              return a*b;
                          }
                   }

                   let mySquare = Square();
                   println("Area :\(mySquare.findArea())");

                   let myRectangle = Rectangle()

                   println("Area :\(myRectangle.findArea())");


In the above snippet a protocol named Area has been created,  and two classes(Square, Rectangle) are inherited the protocol(Area). Protocol properties a, b are used with 'get' attributes. Similarly the properties can be used with 'get set' attributes as well.

Extensions:

                  Extensions are similar to categories in Objective-C, through which we can add new property/ functionality to a class or structure or enum. Adding a new property/ functionality is however doesn't override the existing functionality of a class or structure or enum. Consider the simple example of extension below
         
          extension Int {
                   func repetitions(task: () -> ()) {
                             for i in 1..self {
                               task()
                            }
                  }
          }

         var intVar : Int = 5
         intVar.repetitions{println("hello")}
        
       Here, the extension is added to the class Int, in the extension a new function is added named 'repetitions'. After the extension of this Int, the Int variables are added with a functionality repetitions, which prints the string "hello" the number Integer assigned to the Int variable. In Swift the extensions is very clean to understand, So the snippet provides enough information about Extensions in Swift.

Note: Extensions doesn't have any name in Swift.

Special Features:

Generics:

                Generics  provides a common signature/ template to functions and structures. This feature helps to integrate/ generalise all the functions or structures that have common functionality. So, the flexibility and reusability of functions/ structures are increased.

E.g., Generic function to swap two values by address.
              func swapTwoValues<T>(inout a: T, inout b:T){
                     //here the T is the placeholder/ type-parameter.
                    let temp = a
                    a = b
                    b = temp
              }

var X = 10; var Y = 20;
swapTwoValues(&X, &Y);
println(" X : \(X) , Y : \(Y)");

Here, the swapTwoValues is inferred to Int(Since the parameters passed are of type Int), and so it swaps two Ints based on their addresses.

//similarly , swap two strings....
var A = "welcome"; var B = "hello";
swapTwoValues(&A, &B);

println(" A : \(A) , B : \(B)");


Now, the swapTwoValues is inferred to String, and so the swapping done based on their address.

Note: The idea of this course is how you can approach swift and incorporate the special features into your iOS development. So, the above snippet provides you the knowledge of how to approach Generics. Here the key to be noted is <T>(type-parameter/ placeholder).


Type parameter : 
                          The generics function name is immediately followed by a type parameter '<T>', this denotes that the function / structure belongs to generics.

     Type Constraints:
                                   It is possible to set a constraint for type parameter, So that we can ensure that the       type parameter is fulfils all the required constraints. Below snippet ensures that the type parameters          T, U fulfils the constraints specified in the respective class and protocol.

      func newGeneric< T : SampleClass , U: SampleProtocol> ( t : T , u : U){
      // newGeneric definition goes here...
      }

      Here, the type-parameter T should be a subclass of SampleClass and type-parameter U should conform to the protocol SampleProtocol (For protocol conforming, see the 'Protocol' topic from this course).


Closures : 

                Closures are similar to Blocks in Objective-C.  A block of statements that are used to pass around across the application. Closures behaves just like Blocks in Objective-C, with the some optimization techniques.
The general syntax for the closure is

{ (parameters ) -> ( return-type) in
   //closure definition
}

Starts with a open-curly-brace({) , parameter list, '->' indicating that there exists a return type, and the existing return type, 'in' keyword specifies the Closure definition begins proceeding that, followed by the closure definition, and a closing-curly-brace(}).

      Global functions that doesn't get any value from outside scope, Nested functions that get values from it's outer scope are also defined as a special type of Closures. Consider the below simple example for Closures.

func newSort( a : Int , closure:()-> Void) -> Void{    
    println("This is inside newSort")
    closure()
}
newSort(10, { () -> (Void) in
    println("inside the closure")

})

Here, the newSort() is the function has two parameters, an Integer value and a closure as parameters.

Note: The function call is used to pass the values to the function. Here the values are 10 (an Int value), {()->Void) in println("inside the closure")}  - (a closure which contains the closure definition). It's really important to know that on function call only the closure definition has to be included. In the callee ie., the function definition closure just has the signature of the closure as a parameter.

The above snippet gives the result in the console as

"This is inside newSort
  inside the Closure"
  
    There are some optimization techniques to make the Closure look simple and meaningful. 
Consider the below snippet 

func demoFunc( a : Int , closure:(Int)-> Void) -> Void{
    
    println("This is inside demoFunc")
    closure(a)
}

demoFunc(10, { (a : Int) -> (Void) in
    println("A : \(a)")
})

1. Shorthand argument notation
   
      The function call demoFunc() can be optimized.

     un-optimized function call
     demoFunc(10, { (a : Int) -> (Void) in
          println("A : \(a)")
     })
 
     optimized function call
      demoFunc(10, { a in  println("A : \(a)") })
  
 
2. Trailing closure syntax
 
     If our closure definition is too big, and it's specified at the last of the function call. Then the closure can be trailed with the function call.
    demoFunc(10) { a in println("A : \(a)") }

Note:  For the alternate to the above optimization is,  Closures and functions can be assigned to variables, those variables can be used in the function/ closure entries instead. While assigning closure/ function to a variable no optimization should be taken place.


Multiple return types : 

                                     This feature is something that every developer was longing for. Sometimes it's really needed to return multiple values from a function call, to reduce the no. of global variables. ie., a value used in a single function which is declared globally because of restriction to return only one value from a function call.
Returning a tuple on a function call
eg., func tupleReturning (var1 : Int, var2: Int) -> (Int, Int, Int) {

           return (var1,var2,var1+var2);
}

Here three values together returned as a tuple as you can see from the above snippet. Now the caller should receive the return values in a object as below.

var receiveObject = tupleReturning(10,20);

We can get each values by using the index as below.

var firstValue = receiveObject.0       // 10
var secondValue  = receiveObject.1 // 20
var thirdValue = receiveObject.2      // 30


NameSpaces :

                               Namespace in Swift is very implicit just like Objective-C. That is it's not necessary to 'use namespace' or 'package' kind of things explicitly. In Objective-C, each interface(.h) or implementation(.m) file are inside each unique namespaces. So, that if we want to use/ bring another class(.h) we have to import the class at the top of the required file. But in Swift it's not necessary to import another class used in the same project. In a nutshell, Swift extends the namespace of Objective-C from per file to per target.
                             
                              But however, if we want to use other class variable in a class, we have to simulate it with an variable/object similar to objective-C
ie.,
               If I'm in "SecondViewController.swift", I want to use  a variable in a class FirstViewController at the file "FirstViewController.swift", I have to simulate an object/variable with the required class.
                class SecondViewController{
                .
                .                
                      var firstVC = FirstViewController()
                      firstVC.myVar1 =  self.myVar2

                }
   Here, the firstVC is simulated with the class FirstViewController(), So that the data members of FirstViewController() can be accessed by SecondViewController. Please note that, there is no need of importing the file "FirstViewController.swift" at the top.

Swift Characteristics:


                           The Swift Programming Language has the following characteristics, as Apple has emphasized during the introduction of Swift at the WWDC2014 developer conference.


FAST : 
              The Swift code is very concise. So, the development is very faster and efficient comparing with Objective-C.

MODERN:
                   The modern programming concepts like Generics, Closures and Namespaces are included in Swift.

INTERACTIVE: 
                               Playground is the technique makes the development very interactive, and allows the developer to know how their changes affect the application, very instantly.  

SAFE:
              Type-safety and general safety are much better in Swift. Type-safety is achieved by performing type-checking on compile time. The errors are flagged at the completion of compiling and get unchecked / rectified.

                   The above characteristics are summary of the Swift functionalities. As I told in the beginning, this course of tutorial is not meant to tell you "How to write Swift programming", But this course is to "How to approach Swift" from iOS perspective. With this explanation I would like to end this course of tutorial here, Please give your valid feedback on this course of tutorial. Thanks :-)