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

斯威夫特 – ‘[任务]?不可转换为’Optional <[Any]>&#39

发布时间:2020-12-14 04:38:52 所属栏目:百科 来源:网络整理
导读:我做了扩展 extension Optional where Wrapped == [Any] { var isNilOrEmpty: Bool { get { if let array = self { return array.count == 0 } else { return false } } }} 然后我尝试像这样使用它 if fetchedResults.fetchedObjects.isNilOrEmpty { ... }
我做了扩展

extension Optional where Wrapped == [Any] {
   var isNilOrEmpty: Bool {
       get {
           if let array = self {
              return array.count == 0
           } else {
            return false
           }
       }
    }
}

然后我尝试像这样使用它

if fetchedResults.fetchedObjects.isNilOrEmpty { ... }

我收到了错误

‘[Task]?’ is not convertible to ‘Optional<[Any]>’

但是,按照规范

Any can represent an instance of any type at all,including function types.

这里我的错误是什么?
如果重要的话,Task是NSManagedObject的子类.

解决方法

好吧,[Task]和[Any]是两种不同的类型,Wrapped == [Any]不起作用.

正确的方法是限制Wrapped by protocol,而不是特定的类型.

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        get { // `get` can be omitted here,btw
            if let collection = self {
                return collection.isEmpty // Prefer `isEmpty` over `.count == 0`
            } else {
                return true // If it's `nil` it should return `true` too
            }
        }
    }
}

(编辑:李大同)

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

    推荐文章
      热点阅读