Swift 2.0 for programmers Part#2


Arrays

let daysInWeek = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]

var numbers = [3, 5, 7]

var errorArray = [3, "Hello"]       // compile error, not type safe

// daysInWeek.append("New String") // compile error, constant array declared with let 

// arrays without initial value 
var colors : [String]
colors = ["Red", "Green"]
colors.append("Blue") // ["Red", "Green", "Blue"]

print("First Color: \(colors [0])") // "First Color: Red\n"

colors [0] = "White"
colors += ["Black"]     // ["White", "Green", "Blue", "Black"]
colors.insert("Yellow", atIndex: 2) // ["White", "Green", "Yellow", "Blue", "Black"]

colors.count            // 5
colors.removeLast()     // "Black"
colors.removeAtIndex(2) // "Yellow"
colors.removeAll()      // []
colors.isEmpty          // true 

for day in daysInWeek {
    print(day)
}

Points to be noted

  • Arrays are typed
  • Arrays are mutable when created with var
  • Arrays are immutable when crated with let

Dictionary

var persons = ["John" : 25, "Kate" : 18, "James" : 35]

var personsDict : [String : Int]    // key : value

print(persons ["John"])             // "Optional(25)\n"

persons ["Bill"] = 31               // creates a new one OR change the value if exist already

persons.updateValue(35, forKey: "Mac")  // same as persons ["Mac"] = 35

// if updateValue returns nil, it means, the key-value pair gets inserted 
// if updateValue returns a value, it means, the key-value pair gets updated 

print(persons) // "["Bill": 31, "John": 25, "Kate": 18, "James": 35, "Mac": 35]\n"

persons ["Mac"] = nil       // this will remove both key: Mac and its value 35 from dictionary 

persons.count       // 4

for (key, value) in persons {
    print("Key: \(key) and Value: \(value)")
}

Optionals


var age : Int?  // age may have a value or may not, if no value then it will contain nil

print("Age is: \(age)") // "Age is: nil\n" (currently no value assigned) 

if age != nil {
    print("age has value: \(age)")
}

age = 5

if age != nil {
    print("age has value: \(age)")  // "age has value: Optional(5)\n"
    print("age has value: \(age!)")  // "age has value: 5\n" (force unwrap, as we checked for nil, we are sure it has value)
}

var persons = ["John" : 35, "Kate" : 18]

var result = persons ["Kate"] // result is by default an optional variable
// because it may or may not have a value, depending on key 

if let res = persons ["John"] {
    print (res) // we do not need to unwrap. This line will execute if res != nil
} else {
    // do not try to access "res" variable here. As if we are inside else case, "res" doesn't exist
}

Tuple

var aTuple = ("Hello", 10)      // (.0 "Hello", .1 10)

func aFunction() -> (String, Int, String) {
    return ("A", 5, "B")
}

let res = aFunction()           // (.0 "A", .1 5, .2 "B")

print("A: \(res.0) Int: \(res.1) B: \(res.2)")  // "A: A Int: 5 B: B\n"

func anotherFunc() -> (name: String, age: Int, id: String) {
    return ("John", 35, "Doe")
}

let res1 = anotherFunc()        // (.0 "John", .1 35, .2 "Doe")

print("Name: \(res1.name) age: \(res1.age) id: \(res1.id)") // "Name: John age: 35 id: Doe\n"

let (res2, res3, res4) = anotherFunc()

print("Name: \(res2) age: \(res3) id: \(res4)") // "Name: John age: 35 id: Doe\n"

Enum

enum UserStatus {
    case LoggedIn
    case InActive
    case LoggedOut
}

var aUserStatus : UserStatus

aUserStatus = UserStatus.LoggedIn
aUserStatus = .InActive

switch aUserStatus {
case .LoggedIn:
    break
case .InActive:
    break
case .LoggedOut:
    break
    
    // no need for default, as Swift can recognize we are being exhaustive about values
}

Closures

let aClosure = {
    print("Hello world")
}

// this function accepts a closure as parameter
func aFunction(closureParameter : () -> () ) {
    
    for _ in 1...3 {
        closureParameter()
    }
}

// to call 
aFunction(aClosure)
aFunction({ print("Hello Swift") })
aFunction({ () -> () in
    print("Hello Swift")
})

Points to be noted

  • Closures group code into a self-contained, reusable unit
  • Functions are a type of closure
  • Closure doesn’t have a name unlike functions
  • In other languages its called: Anonymous Functions / Lambdas / Blocks
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s