How do you use the Optional variable in a ternary conditional operator?

前端 未结 6 1414
深忆病人
深忆病人 2021-01-30 10:23

I want to use an Optional variable with the ternary conditional operator but it is throwing error this error: optional cannot be used as boolean. What am I doing wrong?

6条回答
  •  天涯浪人
    2021-01-30 11:04

    Nil Coalescing Operator can be used as well. The code below uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise

    Normal Ternary Operator :

    output = a != nil ? a! : b Apple Developer Link : Please refer to Demo Link

    In Swift 1.2 & 2, above line of code is replaced by a shorter format:

    output = a ?? b
    

    Demo Link : The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

提交回复
热议问题