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))
  }
4

0 回答 0