gpt4 book ai didi

swift 4 : generic conforming to AnyObject does not accept a protocol conforming to AnyObject

转载 作者:行者123 更新时间:2023-11-28 07:55:47 26 4
gpt4 key购买 nike

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

  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):

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

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

    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 提供的链接:

  1. 这是一个(有点)错误:https://bugs.swift.org/browse/SR-55 , 它仍然存在于 Swift 4 中
  2. 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com