且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift泛型数据结构(协议类型)中使用弱引用?

更新时间:2022-06-05 21:39:06

我在玩耍时发现:

// Array of weak references of a protocol OK so long as protocol marked @objc
@objc protocol P { // Note @objc
    var i: Int { get }
}
class CP: P {
    var i: Int = 0
}
let weakPs: [WeakReference<P>] = [WeakReference(value: cP)] // Note typed as `[WeakReference<P>]`
print("P: \(weakPs[0].value!.i)") // 0

有效:)

令人讨厌的是,您必须使用@objc,因此不能使用纯粹的Swift解决方案,但是由于我在iOS上使用,这对我来说不是问题.

It is annoying that you have to use @objc and therefore not a pure Swift solution, but since I am on iOS not a problem for me.