chicobermuda chicobermuda - 1 month ago 4x
Swift Question

Ternary Conditional Operator for else if

I can use the ternary conditional operator for an

if {} else {}
statement like this:
a ? x : y
, or
question ? answer1 : answer2

Is it possible to use this format with an
else if
clause? E.g. something like:

a ? b ? x : y : z

...or is this just overkill?


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


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

or even

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