Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 223
Yashwanth Reddy Avatar asked Nov 12 '14 07:11

Yashwanth Reddy


People also ask

How do you use a ternary conditional operator?

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.

How do you assign a value to a ternary operator?

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


2 Answers

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.

like image 55
Dharmesh Kheni Avatar answered Sep 20 '22 12:09

Dharmesh Kheni


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.

like image 37
Abhijeet Avatar answered Sep 21 '22 12:09

Abhijeet