我需要创建一个类型安全的弱引用数组
一个包含“类型安全”弱引用并且可以是数组元素的结构:
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):
protocol LemmingTrackingProtocol: AnyObject { func onLemmingZPositionChanged() func onLemmingDrop() }
这是可能的:
var trackers = [WeakRef<LemmingTrackingProtocol>]()
但这不是:
func addTracker(_ tracker: LemmingTrackingProtocol) { let tracker = WeakRef(tracker) // <-- Cannot invoke initializer... ... }
请提示我做错了什么。谢谢!
最佳答案
长话短说:
只需将 @objc
添加到所需的协议(protocol)(在我的例子中是 LemmingTrackingProtocol
)
警告
虽然这有效,you'll probably get stuck with not being able to create an extension with your @objc
protocol
详细
根据@Hamish 提供的链接:
- 这是一个(有点)错误:https://bugs.swift.org/browse/SR-55 , 它仍然存在于 Swift 4 中
- protocols do not (should not) always conform to themselves
关于 swift 4 : generic conforming to AnyObject does not accept a protocol conforming to AnyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48102270/