Last active
March 2, 2017 08:31
-
-
Save bwhiteley/002d1110e6142f56e705 to your computer and use it in GitHub Desktop.
NilLiteralConvertible can lead to surprising behavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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