Swift Intermediate

From Hawk Wiki
Revision as of 00:12, 27 January 2015 by Hall (Talk | contribs) (Optional Type)

Jump to: navigation, search

Intermediate Swift

Reference [WWDC Link]

Optional Type

var optionalNumber = Int?
//default init to nil
optionalNumber = 9

Non-optional type cannot be nil

Example

func findIndexOfArray(needle: String, array: String[]) => Int? {
  for (index, value) in enumerate(array) {
    if value == needle {
      return index
    }
  }
  return nil
}
var neighbors = ["Alex", "Anna", "Madison"]
let index = findIndexOfArray("Alex", neighbors)
if index {
  println("Found \(neighbors[index!])") // noticing the !. The ! will unwrapping the value. Must check non-nil it before unwrap.
}
//Optional binding: Check and unwrap at same time
if let indexValue = findIndexOfArray("Alex", neighbors) {
  println("Found \(neighbors[indexValue])")
}

Optional Chaining

Example Without Chaining:

var addressNumber: Int?
if let home = paul.residence {
  if let postalAddress = home.Address {
    if let building = postalAddress.buildingNumber {
      if let convertedNumber = building.toInt() {
        addressNumber = converttedNumber
      }
    }
  }
}

With Chaining

addressNumber = paul.residence?.address?.buildingNumber?.toInt()
//addressNumber is still an optional value at this state
//Combine again
if let addressNumber = paul.residence?.address?.buildingNumber?.toInt() {
  addtoDb("paul", addressNumber)
}