Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign conditional expression in Swift?

Tags:

swift

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

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

(or with a switch case).

(Don't want to have to use ternary operator for this).

This kind of assignement is good for functional style / immutability. The expressions have a return value in this case.

Note: it's a general question, this is just simplified example, imagine e.g. a switch case with a lot of values, pattern matching, etc. You can't do that with ternary operator.

Btw also note that there are languages that don't support ternary operator because if else returns a value, so it's not necessary, see e.g. Scala.

like image 334
User Avatar asked Dec 05 '14 12:12

User


People also ask

What does ~= mean in Swift?

The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The matches succeeds if the ~= operator returns true . By default, the ~= operator compares two values of the same type using the == operator.


1 Answers

You can use a closure to initialize an immutable:

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

The advantage of using a closure is that it's a function, so you can use any complex logic inside, implemented in a clean way and not through nested ternary operators. It can be a switch statement, it can be obtained as the return value of a function followed by some calculations, it can be a pattern matching case, it can be a combination of them all, etc.

Said in other words, it's the same as initializing with the return value of a function, but the difference is that the function is inline and not somewhere else, with readability benefits.

Just for completeness, if the variable is mutable, you can use deferred initialization:

var foo: Int

// Any statement here

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

// Other statements here

myFunc(foo)

so you can declare a mutable variable, and initialize it anywhere in the same scope, but before using it the variable must be initialized.

Update: Since Swift 2.0, deferred initialization also works with immutables.

like image 51
Antonio Avatar answered Oct 15 '22 11:10

Antonio