检查可选布尔值 [英] Checking the value of an Optional Bool

查看:217
本文介绍了检查可选布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想检查Optional Bool是否为真时,这样做不起作用:

When I want to check if an Optional Bool is true, doing this doesn't work:

var boolean : Bool? = false
if boolean{
}

它导致此错误:

可选类型'@IvalueBool?'不能用作布尔值;测试'!= nil' 代替

Optional type '@IvalueBool?' cannot be used as a boolean; test for '!= nil' instead

我不想检查零;我想检查返回的值是否为真.

I don't want to check for nil; I want to check if the value returned is true.

如果我正在使用可选的Bool,是否总是必须执行if boolean == true?

Do I always have to do if boolean == true if I'm working with an Optional Bool?

由于Optionals不再符合BooleanType,编译器不应该知道我要检查Bool的值吗?

Since Optionals don't conform to BooleanType anymore, shouldn't the compiler know that I want to check the value of the Bool?

推荐答案

带有可选的布尔值,需要使检查明确:

With optional booleans it's needed to make the check explicit:

if boolean == true {
    ...
}

否则,您可以打开可选包装:

Otherwise you can unwrap the optional:

if boolean! {
    ...
}

但是如果boolean为nil,则会生成运行时异常-防止发生这种情况:

But that generates a runtime exception if boolean is nil - to prevent that:

if boolean != nil && boolean! {
    ...
}

有可能在beta 5之前,但它已根据发行说明中的​​内容进行了更改:

Before beta 5 it was possible, but it has been changed as reported in the release notes:

当具有可选值时,可选选项不再隐式评估为true,否则将不再隐式评估为false,以避免在使用可选Bool值时产生混淆.相反,请使用==或!=运算符对nil进行显式检查,以找出可选值是否包含值.

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.

附录:如@MartinR所建议,对第3个选项的更紧凑的变化是使用合并运算符:

Addendum: as suggested by @MartinR, a more compact variation to the 3rd option is using the coalescing operator:

if boolean ?? false {
    // this code runs only if boolean == true
}

表示:如果布尔值不为nil,则表达式的计算结果为布尔值(即使用展开的布尔值),否则表达式的计算结果为false

which means: if boolean is not nil, the expression evaluates to the boolean value (i.e. using the unwrapped boolean value), otherwise the expression evaluates to false

这篇关于检查可选布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆