swift - '[任务] ?' is not convertible to ' 可选<[任何]>'

标签 swift generics types type-conversion option-type

我做了扩展

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] 不会起作用。

正确的方法是通过协议(protocol)限制Wrapped,而不是特定类型。

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
            }
        }
    }
}

关于swift - '[任务] ?' is not convertible to ' 可选<[任何]>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652923/

相关文章:

.net - 为什么我需要 Typescript 中的泛型

c++ - 将 vector<char> buf(256) 转换为 LPCSTR?

c# - 实现通用 OrderBy 解决方案时遇到问题

ios - Swift 字典获取值的键

ios - 生成具有给定分布的随机数

范围对象的 Swift 数组/字典

java - Java有界通用协方差

haskell - 将函数映射到字符串

methods - 静态类型语言中的多界方法?

ios - 滚动表格 View 时单元格变为空白(快速)