chicobermuda - 10 months ago 40

Swift Question

I can use the ternary conditional operator for an

`if {} else {}`

`a ? x : y`

`question ? answer1 : answer2`

Is it possible to use this format with an

`else if`

`a ? b ? x : y : z`

...or is this just overkill?

Answer

Both `x`

and `y`

in `a ? x : y`

are complete expressions, so you are allowed to put any kind of sub-expressions into them, as long as they produce results of the correct type.

However, nesting of conditional expressions quickly becomes unmanageable, so using parentheses is a very good idea:

```
let res = a ? (b ? x : y) : z
```

or

```
let res = a ? x : (b ? y : z)
```

or even

```
let res = a ? (b ? w : x) : (c ? y : z)
```

Source (Stackoverflow)