简体   繁体   English

如何在三元条件运算符中使用 Optional 变量?

[英]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.我想使用带有三元条件运算符的 Optional 变量,但它抛出错误这个错误:可选不能用作布尔值。 What am I doing wrong?我究竟做错了什么?

var str1: String?
var myBool:Bool
myBool = str1 ? true : false

You can not assign string value to bool but You can check it str1 is nil or not like this way :您不能将字符串值分配给 bool 但您可以像这样检查 str1 是否为零:

myBool = str1 != nil ? true : false
print(myBool)

It will print false because str1 is empty.它将打印 false 因为 str1 是空的。

Nil Coalescing Operator can be used as well.也可以使用 Nil Coalescing Operator。 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下面的代码使用三元条件运算符和强制解包 (a!) 在 a 不为 nil 时访问包裹在 a 中的值,否则返回 b

Normal Ternary Operator :普通三元运算符:

output = a != nil ? a! : b output = a != nil ? a! : b Apple Developer Link : Please refer to Demo Link output = a != nil ? a! : b Apple Developer Link : 请参考演示链接

In Swift 1.2 & 2, above line of code is replaced by a shorter format:在 Swift 1.2 & 2 中,上面的代码行被更短的格式替换:

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.演示链接: nil 合并运算符 (a ?? b) 如果包含值则解包可选的 a,如果 a 为 nil,则返回默认值 b。

如果您想要的值是一个属性或一个可选的函数调用的结果(在 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).和 C 一样,Swift 只有一个三元运算符,即三元条件运算符 (a ? b : c)。

Example usage on tableView - 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.指示如果部分等于 2,则返回 4,否则返回 1 为假。

To add on the already very good answers, sometimes you need the convenience of the ternary operator but also need to perform changes on the wrapped value, such as;为了补充已经非常好的答案,有时您需要三元运算符的便利性,但也需要对包装的值进行更改,例如;

var fullName = lastName != nil ? "\(firsName) \(lasName!)" : firstName

But you don't want to force unwrap (even though this situation would be fine).但是您不想强制展开(即使这种情况会很好)。

Then you can actually use Optional.map :然后你可以实际使用Optional.map

var fullName = lastName.map({ "\(firstName) \($0)" }) ?? firstName

The completion block passed to .map is only called if the wrapped value ( $0 ) is not nil .传递给.map的完成块仅在包装值( $0 )不为nil时才被调用。 Otherwise, that function just returns nil , which you can then easily coalesce with the ??否则,该函数只返回nil ,然后您可以轻松地将其与?? operator.操作员。

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.这里函数 getLocationRadius() 返回一个字符串。 One more thing if we don't put a space between 1 and ?如果我们不在 1 和 ? it results in an syntax error它导致语法错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM