Swift 4:符合AnyObject的泛型不接受符合AnyObject的协议

时间:2018-01-04 19:31:58

标签: swift generics protocols

我需要创建一个类型安全的弱引用数组

  1. 一个包含'类型安全'弱引用的结构,可以是数组的元素:

    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
        }
    }
    
  2. 我有一个需要与这个弱参考使用的协议:

    protocol LemmingTrackingProtocol: AnyObject {
        func onLemmingZPositionChanged()
        func onLemmingDrop()
    }
    
  3. 这是可能的:

    var trackers = [WeakRef<LemmingTrackingProtocol>]()
    
  4. 但这不是:

    func addTracker(_ tracker: LemmingTrackingProtocol) {
        let tracker = WeakRef(tracker) // <-- Cannot invoke initializer...
    
        ...
    }
    
  5. 请告诉我一些我做错了什么。谢谢!

1 个答案:

答案 0 :(得分:0)

<强> TL; DR:

只需将@objc添加到所需的协议(在我的情况下为LemmingTrackingProtocol

警告

虽然这有效,you'll probably get stuck with not being able to create an extension with your @objc protocol

<强>详细

根据提供的@Hamish链接:

  1. 这是一个(某种)错误:https://bugs.swift.org/browse/SR-55,它仍然存在于Swift 4中
  2. protocols do not (should not) always conform to themselves