This is a series of tutorial on swift programing language.

Variables

It provides all main types for:

  • Int and Bool
  • String
  • Double and Float
  • Array and Collection
  • Optional types, these types could contain either some a value or nil

    //Assigning
    var x: String
    x = nil //Error
    
    
    var x: String?
    x = nil //Valid since x is optional
    

Creating Variables:

  • Inferred type
    Variable will type be inferred from the assignment

    var a = "Test" 
    
  • Annotated type
    Annotate a variable with the Type

    var a:String = "Test"
    
  • Constants

    let a = 1
    

Type Aliases

typealias X = Int
//X can be use as Int
var a: X

Code is similar to typedef in c

Tuple

Tuple is a group of multiple values

  • Creating a tuple

    //Tuple without naming
    var point = (1,2)
    //Getting a value
    var x = point.0
    
    
    //Tuple with naming 
    var point = (x: 1, y: 2)
    //Getting a value
    var x = point.x
    
  • Assigning both vars (x,y)

    var (x, y) = point
    
  • Ignoring some values, only assign y

    var (_, y) = tup
    

Optional

Swift can contain optionals, optional either have a value or have none, Optionals are denoted by a Type followed by ?

//Creating Optional
var x = "123"
var i = x.toInt() //toInt return Int?

In order to use optional you have to 1)check that its not nil, and 2)unwrap it,
To unwrap an optional add a ! after the object

if i {
  var unwrapped = i! //Now you can use i! or unwrapped like an Int
}

Another way of using optional is by Binding

if let unwrapped = i {
  //Use unwrapped
}
Implicitly Unwrapped Optionals

Is a special case of an optional that is automatically unwrapped without using the ! when accessing
They are defined by adding a ! after the Type name

var str: String!

They the exact rules of the optionals

Collections

Arrays
Creation

Arrays are type safe the type is either inferred or explicitly set

//Inferred type
var a = [1,2,3]

//Explicit Empty array
var a = Array<Type>()
var a = Type[]()
Alteration

You can add a new element by calling append arr.append("new") or by using += operator arr += "new"

Using Range in the subscript of the array will return a sub array

var a = [1,2,3,4,5,6,7]
var b = a[2..5]

Array can be used as a Stack by using append/removeLast in place of push/pop

Iteration

Iterate the items using for in or iterate with index using enumerate

for (index, value) in enumerate(shoppingList) {
}
Dictionary
Creation

Dictionaries are type safe the type is either inferred or explicitly set

//Inferred type
var a = ["k1":1, "k2":2]

//Explicit Empty Dictionary
var a = Dictionary<Type, Type>()
Alteration

You can add a new element by calling append dict["key"] = "new" setting the key to nil will remove it

Iteration

Iterate the items using for (tuple) in

for (key, value) in enumerate(shoppingList) {
}