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

Yashwanth Reddy picture Yashwanth Reddy · Nov 12, 2014 · Viewed 61k times · Source

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

Answer

Dharmesh Kheni picture Dharmesh Kheni · Nov 12, 2014

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.