Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Conditional Operator for else if

Tags:

swift

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?

like image 819
slider Avatar asked Mar 12 '23 05:03

slider


1 Answers

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)
like image 93
Sergey Kalinichenko Avatar answered Mar 19 '23 16:03

Sergey Kalinichenko