Skip to content

Instantly share code, notes, and snippets.

@coryalder
Last active January 23, 2016 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryalder/67ef6ce911c65d74a479 to your computer and use it in GitHub Desktop.
Save coryalder/67ef6ce911c65d74a479 to your computer and use it in GitHub Desktop.
// This code does not compile without the following two changes
//
// 1. add ! to the type of expensiveThing (`String!`)
// 2. expensiveThing = nil // set expensiveThing to nil
//
// This doesn't really make sense to me. Why should I be forced to finish setup, if I'm going to fail?
// The swift book explains that this is required, but not the logic behind it:
// https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_339
// Search for "Failable Initializers for Classes"
//
class Demo {
let expensiveThing: String // String!
init?(shouldMake: Bool) {
if shouldMake {
expensiveThing = "tacos!"
} else {
// expensiveThing = nil
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment