Single line if statement in Swift Single line if statement in Swift ios ios

Single line if statement in Swift


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 calleda >= 0 ? doThis(): doThat()func doThis() {    println("Do This")}func doThat() {    println("Do That")}


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 linerif (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 = trueBool somethingElse = trueif (anUnrelatedCondition)     something = false    somethingElse = falseprint something // outputs trueprint somethingElse // outputs false


You can use new Nil-Coalescing Operator, since Swift 3 in case when you need just set default value in case of if fails:

let someValue = someOptional ?? ""

In case if someOptional is false, this operator assign "" to someValue

var dataDesc = (value == 7) ? "equal to 7" : "not equal to 7"