我需要创建一个类型安全的弱引用数组
一个包含'类型安全'弱引用的结构,可以是数组的元素:
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
}
}
我有一个需要与这个弱参考使用的协议:
protocol LemmingTrackingProtocol: AnyObject {
func onLemmingZPositionChanged()
func onLemmingDrop()
}
这是可能的:
var trackers = [WeakRef<LemmingTrackingProtocol>]()
但这不是:
func addTracker(_ tracker: LemmingTrackingProtocol) {
let tracker = WeakRef(tracker) // <-- Cannot invoke initializer...
...
}
请告诉我一些我做错了什么。谢谢!
答案 0 :(得分:0)
<强> TL; DR:强>
只需将@objc
添加到所需的协议(在我的情况下为LemmingTrackingProtocol
)
警告强>
虽然这有效,you'll probably get stuck with not being able to create an extension with your @objc
protocol
<强>详细强>
根据提供的@Hamish链接: