Skip to content

Instantly share code, notes, and snippets.

@drodriguez
Created June 22, 2014 23:50
Show Gist options
  • Save drodriguez/980cf595e5811ec88dfa to your computer and use it in GitHub Desktop.
Save drodriguez/980cf595e5811ec88dfa to your computer and use it in GitHub Desktop.
Abusing optional syntax for better boolean properties
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")
}
@drodriguez
Copy link
Author

Output:

t1 is enabled
t1 is enabled (without question mark)
t2 is not enabled
t2 is not enabled (without question mark)
t3 is not enabled
t3 is enabled
t3 is not enabled

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment