Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Optionals and Enums - dotSwift 2015

Swift Optionals and Enums - dotSwift 2015

Opening talk from dotSwift 2015 (dotSwift.io), the first ever Swift conference.
Video available at www.youtube.com/watch?v=DTAs_OVGWIs

"For Dimitri, the announcement of Swift was not a revolution but a revelation. In this opening talk at dotSwift, he explores a few "Swiftisms" like Optionals and Enums."

Dimitri Dupuis-Latour

February 06, 2015
Tweet

More Decks by Dimitri Dupuis-Latour

Other Decks in Programming

Transcript

  1. Swift•is•m (swɪftɪzəm) adj. circa 2015 A Swift idiom or pattern

    showing the safer, compact, and expressive nature of Swift, usually not achievable in Objective-C
  2. June 4th : Write actual code UILabel? doesn’t have a

    text property fatal error: unexpectedly found nil while unwrapping an Optional value Value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?
  3. If let statement if let realCat = cat { //

    cat is not nil println("Hurray, \(realCat.name) is alive !") } else { // cat is nil println("Sorry, your cat is dead…") }
  4. Optionals var a:String? • Model a null state • Tell

    the compiler
 « this could be nil » • Anything else has a value
  5. Making your code safer • Eliminates whole class of bugs

    • nil-related crashes • uninitialized variables • incomplete object initialization • Eliminates useless nil-checks • Forces necessary nil-checks
  6. « In theory, there is no difference between theory and

    practice. In practice, there is »
  7. One Table View, 4 States Loading Items Book 1 Book

    2 Book 3 Book 4 Book 5 Book 6 Book 7 Error Error Occurred Unable to connect to host api.abc.com/v1/example Empty No Item yet Start by adding your first item Add Item NSError [Book]
  8. Swift enums enum State { case Loading case Error case

    Empty case Items } var state:State = .Loading var data:[Book]? var error:NSError?
  9. Swift enums enum State { case Loading case Error(NSError) case

    Empty case Items([Book]) } var state:State = .Loading Enum Associated Values
  10. Associated Values switch state { case .Loading: println("Loading") case .Error(let

    error): println("Error: \(error.localizedDescription)") case .Empty: println("Empty") case .Items(let items): println("They are \(items.count) items in the array") }
  11. Enum Associated Values • Associated Values help reduce state •

    Protects access to data • Enforced by compiler