Swift Intermediate

From Hawk Wiki
Revision as of 00:34, 27 January 2015 by Hall (Talk | contribs) (Initialization)

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)
}

Optionals Under the Hood

enum Optional<T> {
  case None
  case Some(T)
}

Automatic Reference Counting

Weak References

Use Weal references among objects with independent lifetimes
weak references are optionals If part of the object goes away, the other objects stay

Unowned References

Use Unowned references from owned objects with the same lifetime
If part of the object goes away, the entire object go away

Initialization

Every value MUST be initialized before it is used
in Class. always set own properties before super.init()

class Car {}
class RaceCar: Car{
  var hasTurbo: Bool
  init(turbo: Bool) {
    hasTurbo = turbo // Do this first
    super.init()
  }
}