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?
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.