我做了扩展 extension Optional where Wrapped == [Any] { var isNilOrEmpty: Bool { get { if let array = self { return array.count == 0 } else { return false } } }} 然后我尝试像这样使用它 if fetchedResults.fetchedObjects.isNilOr
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的子类.
正确的方法是限制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 } } } }