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?
var str1: String? var myBool:Bool myBool = str1 ? true : false
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. result = 'somethingelse'; The ternary operator shortens this if/else statement into a single statement: result = (condition) ?
You can not assign string value to bool but You can check it str1 is nil or not like this way :
myBool = str1 != nil ? true : false print(myBool)
It will print false because str1 is empty.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With