Search code examples
iosobjective-cswiftswift3swift4

Single line if statement in Swift


How would one convert the following to Swift from Objective-C?

if (myVar) return;

Swift does not use parentheses around the conditional, however the following code gives an error.

if myVar return 

Solution

  • 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