加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用可选链接访问NSNumber var中的boolValue(在Swift中)

发布时间:2020-12-14 05:26:01 所属栏目:百科 来源:网络整理
导读:我有一个带有可选实例变量的NSManagedObject子类 @NSManaged var condition: NSNumber? // This refers to a optional boolean value in the data model 当条件变量存在且包含’true’时,我想做一些事情. 当然,我可以这样做: if let cond = condition { if
我有一个带有可选实例变量的NSManagedObject子类
@NSManaged var condition: NSNumber? // This refers to a optional boolean value in the data model

当条件变量存在且包含’true’时,我想做一些事情.

当然,我可以这样做:

if let cond = condition {
 if cond.boolValue {
  // do something
 }
}

但是,我希望通过可选链接可以做一些更紧凑的事情.像这样的东西:

if condition?.boolValue {
  // do something
}

但这会产生编译器错误:

Optional type ‘$T4??’ cannot be used as a boolean; test for ‘!= nil’ instead

解决这个问题最紧凑的方法是:

if condition != nil && condition!.boolValue {
 // do something
}

是否真的没有办法通过可选链接访问布尔值,或者我在这里遗漏了什么?

您可以将它与布尔值进行比较:
if condition == true {
    ...
}

一些测试用例:

var testZero: NSNumber? = 0
var testOne: NSNumber? = 1
var testTrue: NSNumber? = true
var testNil: NSNumber? = nil
var testInteger: NSNumber? = 10

if testZero == true {
    // not true
}

if testOne == true {
    // it's true
}

if testTrue == true {
    // It's true
}

if testNil == true {
    // not true
}

if testInteger == true {
    // not true
}

最有趣的是1被认为是真的 – 这是预期的,因为类型是NSNumber

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读