Difference between revisions of "Swift Intermediate"
From Hawk Wiki
(→Automatic Reference Counting) |
|||
Line 63: | Line 63: | ||
==Automatic Reference Counting== | ==Automatic Reference Counting== | ||
− | + | <h4>Weak References</h4> | |
Use Weal references among objects with independent lifetimes<br> | Use Weal references among objects with independent lifetimes<br> | ||
weak references are optionals | weak references are optionals | ||
If part of the object goes away, the other objects stay | If part of the object goes away, the other objects stay | ||
− | + | <h4>Unowned References</h4> | |
Use Unowned references from owned objects with the same lifetime<br> | Use Unowned references from owned objects with the same lifetime<br> | ||
If part of the object goes away, the entire object go away | If part of the object goes away, the entire object go away |
Revision as of 00:28, 27 January 2015
Contents
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