Skip to content

Instantly share code, notes, and snippets.

@bwhiteley
Last active March 2, 2017 08:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwhiteley/002d1110e6142f56e705 to your computer and use it in GitHub Desktop.
Save bwhiteley/002d1110e6142f56e705 to your computer and use it in GitHub Desktop.
NilLiteralConvertible can lead to surprising behavior
struct Foo : CustomStringConvertible {
let text:String
init(text:String) {
self.text = text
}
var description:String { return self.text }
}
extension Foo : NilLiteralConvertible {
init(nilLiteral: ()) {
self.init(text:"null")
}
}
func f1() -> Foo? {
return nil // This returns .None
}
func f2() -> Foo? {
return true ? nil : Foo(text: "bar") // This returns .Some(Foo)
}
let one = f1()
let two = f2()
if case .None = one {
print("one is .None")
}
if case .None = two { // false
print("two is .None")
}
if let two = two {
print("two is \(two.text)") // We see this!
}
// To achieve what you probably intended, use .None instead of nil
func f2_() -> Foo? {
return true ? .None : Foo(text: "bar") // This returns .None
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment