我创建Observable
类来在Swift中实现观察者模式。当值从旧值更改时,会通知订阅者,因此此泛型类型应符合Equatable协议。
但是当类型为String?
时,Xcode会引发Type 'String?' does not conform to protocol 'Equatable'
错误。
如果我没记错的话,String
和String?
符合Equatable协议......为什么?
import UIKit
final class Observable<T: Equatable> {
typealias ObserverHandler = ((T) -> Void)
typealias ObserverEntry = (owner: AnyObject, didChange: ObserverHandler)
var value: T {
didSet {
if self.value == oldValue { return }
self.observers.forEach({ (entry: ObserverEntry) in entry.didChange(self.value) })
}
}
private var observers: [ObserverEntry] = []
init(_ value: T) {
self.value = value
}
func subscribe(observer: AnyObject, didChange block: @escaping ObserverHandler) {
let entry: ObserverEntry = (owner: observer, didChange: block)
observers.append(entry)
}
func unsubscribe(observer: AnyObject) {
let filteredEntries: [ObserverEntry] = observers.filter({ (entry: ObserverEntry) -> Bool in
return (entry.owner !== observer)
})
self.observers = filteredEntries
}
}
// [!] Type 'String?' does not conform to protocol 'Equatable'
var foo: Observable<String?> = Observable(nil)
答案 0 :(得分:2)
SELECT *
FROM dbc.ColumnsV
WHERE CommentString LIKE '%marketing%'
是String?
的简写。在Swift 4.1之前,没有办法使类型有条件地符合协议。例如。 Optional<String>
仅Optional<T>
Equatable
为T
时才应为Equatable
。
这称为conditional conformance,在Swift 4.1中称为Optional: Equatable where Self.Wrapped: Equatable
。