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

谁说我不能喝 提交于 2019-12-02 15:22:54
Dharmesh

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.

This even works well if the value you want is a property or result of a function call on an optional (in Swift 3.0):

return peripheral?.connected ?? false

Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).

Example usage on tableView -

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return section == 2 ?  4 :  1
}

indicates if section equal to 2 then it return 4 otherwise 1 on false.

In case the comparison is based on some condition

 let sliderValue = Float(self.preferenceData.getLocationRadius().characters.count > 1 ?self.preferenceData.getLocationRadius():"0.1")

Here the function getLocationRadius() returns a String. One more thing if we don't put a space between 1 and ? it results in an syntax error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!