我做了扩展
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/