Created
June 22, 2014 23:50
-
-
Save drodriguez/980cf595e5811ec88dfa to your computer and use it in GitHub Desktop.
Abusing optional syntax for better boolean properties
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
class MyClass { | |
var enabled: Bool? { | |
didSet { | |
if let v = enabled? { | |
self.enabled = v ? true : nil | |
} | |
} | |
} | |
init(enabled: Bool) { | |
self.enabled = enabled ? true : nil | |
} | |
} | |
var t1 = MyClass(enabled: true) | |
if t1.enabled? { | |
println("t1 is enabled") | |
} | |
if t1.enabled { | |
println("t1 is enabled (without question mark)") | |
} | |
var t2 = MyClass(enabled: false) | |
if !t2.enabled? { | |
println("t2 is not enabled") | |
} | |
if !t2.enabled { | |
println("t2 is not enabled (without question mark)") | |
} | |
var t3 = MyClass(enabled: false) | |
if t3.enabled? { | |
println("t3 is enabled") | |
} else { | |
println("t3 is not enabled") | |
} | |
t3.enabled = true | |
if t3.enabled? { | |
println("t3 is enabled") | |
} else { | |
println("t3 is not enabled") | |
} | |
t3.enabled = false | |
if t3.enabled? { | |
println("t3 is enabled") | |
} else { | |
println("t3 is not enabled") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: