为什么"字符串?"不符合Equatable

时间:2018-02-23 18:10:08

标签: swift

我创建Observable类来在Swift中实现观察者模式。当值从旧值更改时,会通知订阅者,因此此泛型类型应符合Equatable协议。 但是当类型为String?时,Xcode会引发Type 'String?' does not conform to protocol 'Equatable'错误。

如果我没记错的话,StringString?符合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)

1 个答案:

答案 0 :(得分:2)

SELECT * FROM dbc.ColumnsV WHERE CommentString LIKE '%marketing%' String?的简写。在Swift 4.1之前,没有办法使类型有条件地符合协议。例如。 Optional<String>Optional<T> EquatableT时才应为Equatable

这称为conditional conformance,在Swift 4.1中称为Optional: Equatable where Self.Wrapped: Equatable