'[任务]?' 不能转换为“ Optional <[Any]>”

Ale*_*hka 4 generics types type-conversion optional swift

我做了扩展

extension Optional where Wrapped == [Any] {
   var isNilOrEmpty: Bool {
       get {
           if let array = self {
              return array.count == 0
           } else {
            return false
           }
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试像这样使用它

if fetchedResults.fetchedObjects.isNilOrEmpty { ... }
Run Code Online (Sandbox Code Playgroud)

我出错了

'[任务]?' 不能转换为“ Optional <[Any]>”

但是,根据规格

Any可以代表任何类型的实例,包括函数类型。

我这是什么错 如果重要,任务是NSManagedObject的子类。

use*_*434 6

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

正确的方法是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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)