Why ternary operator in swift is so picky?

前端 未结 2 1286
日久生厌
日久生厌 2021-01-17 14:43

The question is very simple, but I just could not find the answer!

Why doesn\'t

return x == 0? \"\" : \"Hello\"

compile but

2条回答
  •  情歌与酒
    2021-01-17 15:40

    Yes, I'm pretty sure (as you presumed) the problem is with optionals.

    I prefer to write my ternary operators like this...

    let num = (isTrue) ? (1) : (0)
    

    Of course, you can choose what's in the parentheses, whether it's simply a literal (as shown) or not.

提交回复
热议问题