Assign conditional expression in Swift?

Is there a way in Swift to assign conditional expressions like this

let foo = if (bar == 2) {
        100
    } else {
        120
    }

(or with switch case).

(No need to use the ternary operator for this).

This type of assignment is good for functional style / immutability. In this case, the expressions have a return value.

Note: this is a general question, this is just a simplified example, imagine for example. case switching with a large number of values, matching patterns, etc. You cannot do this with the ternary operator.

Btw also note that there are languages ​​that do not support the ternary operator, because if else returns a value, so this is not necessary, see, for example, Scala .

+2
source share
1

:

let foo: Int = {
    if bar == 2 {
        return 100
    } else {
        return 120
    }
}()

, , , , . switch, , , , ..

, , , , , - , .

, , :

var foo: Int

// Any statement here

if bar == 2 {
    foo = 100
} else {
    foo = 120
}

// Other statements here

myFunc(foo)

, .

. Swift 2.0, .

+8

Source: https://habr.com/ru/post/1612457/


All Articles