1

I have this class in my project:

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

is it possible to make AnyCancellable conforms to Hashable ?

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

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

is this a correct implementation ?

public func hash(into hasher: inout Hasher) {
    hasher.combine(ObjectIdentifier(self))
  }
Bobj-C
  • 5,131
  • 8
  • 45
  • 79
  • 1
    If equality is based on object identity then this is correct, compare e.g. https://stackoverflow.com/a/30345908/1187415. – Martin R Nov 21 '19 at 09:12

0 Answers0