Single line if statement in Swift
In Swift the braces aren't optional like they were in Objective-C (C). The parens on the other hand are optional. Examples:
Valid Swift:
if someCondition {
// stuff
}
if (someCondition) {
// stuff
}
Invalid Swift:
if someCondition
// one liner
if (someCondition)
// one liner
This design decision eliminates an entire class of bugs that can come from improperly using an if statement without braces like the following case, where it might not always be clear that something
's value will be changed conditionally, but somethingElse
's value will change every time.
Bool something = true
Bool somethingElse = true
if (anUnrelatedCondition)
something = false
somethingElse = false
print something // outputs true
print somethingElse // outputs false
Well as the other guys also explained that braces are a must in swift. But for simplicity one can always do something like:
let a = -5
// if the condition is true then doThis() gets called else doThat() gets called
a >= 0 ? doThis(): doThat()
func doThis() {
println("Do This")
}
func doThat() {
println("Do That")
}