如何实现func hash(into hasher:inout Hasher)?

时间:2019-11-21 08:58:11

标签: ios swift hashable swift5.1

我的项目中有此类:

public protocol Disposable {
    func dispose()
    var isDisposed: Bool { get }
}

public final class AnyCancellable: Disposable {

    private let lock = NSRecursiveLock(name: "any_cancellable")
    private var handler: (() -> ())?

    public var isDisposed: Bool {
        lock.lock(); defer { lock.unlock() }
        return handler == nil
    }


    public init(_ handler: @escaping () -> ()) {
        self.handler = handler
    }

    deinit {
        dispose()
    }

    public func dispose() {
        lock.lock()
        guard let handler = handler else {
            lock.unlock()
            return
        }
        self.handler = nil
        lock.unlock()
        handler()
    }

    public func cancel() {
        dispose()
    }
}

是否可以使AnyCancellable符合Hashable?

extension AnyCancellable: Hashable {
  public static func == (lhs: AnyCancellable, rhs: AnyCancellable) -> Bool {
    lhs === rhs
  }

  public func hash(into hasher: inout Hasher) {
   ?????
  }
}

这是正确的实现吗?

public func hash(into hasher: inout Hasher) {
    hasher.combine(ObjectIdentifier(self))
  }

0 个答案:

没有答案