I need to create an array of type-safe weak references
a structure that holds a 'type-safe' weak reference and can be an element of an array:
public struct WeakRef<T: AnyObject>: Hashable { public weak var ref: T? public let hashValue: Int init(_ ref: T) { self.ref = ref self.hashValue = ObjectIdentifier(ref).hashValue } } extension WeakRef: Equatable { public static func ==(lhs: WeakRef<T>, rhs: WeakRef<T>) -> Bool { return lhs.hashValue == rhs.hashValue } } extension WeakRef: Comparable { static public func < (lhs:WeakRef<T>, rhs:WeakRef<T>) -> Bool { return lhs.hashValue < rhs.hashValue } static public func <= (lhs:WeakRef<T>, rhs:WeakRef<T>) -> Bool { return lhs.hashValue <= rhs.hashValue } static public func >= (lhs:WeakRef<T>, rhs:WeakRef<T>) -> Bool { return lhs.hashValue >= rhs.hashValue } static public func > (lhs:WeakRef<T>, rhs:WeakRef<T>) -> Bool { return lhs.hashValue > rhs.hashValue } }
I have a protocol which needs to be used with this weak ref:
protocol LemmingTrackingProtocol: AnyObject { func onLemmingZPositionChanged() func onLemmingDrop() }
this is possible:
var trackers = [WeakRef<LemmingTrackingProtocol>]()
but this is not:
func addTracker(_ tracker: LemmingTrackingProtocol) { let tracker = WeakRef(tracker) // <-- Cannot invoke initializer... ... }
Please kindly give me a hint of what I am doing wrong. Thanks!