如何在Swift中声明一个弱引用数组? [英] How do I declare an array of weak references in Swift?
本文介绍了如何在Swift中声明一个弱引用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Swift中存储一系列弱引用.数组本身不应该是一个弱引用-它的元素应该是.我认为可可NSPointerArray
为此提供了非类型安全的版本.
I'd like to store an array of weak references in Swift. The array itself should not be a weak reference - its elements should be. I think Cocoa NSPointerArray
offers a non-typesafe version of this.
推荐答案
创建通用包装器为:
class Weak<T: AnyObject> {
weak var value : T?
init (value: T) {
self.value = value
}
}
将此类的实例添加到您的数组中.
Add instances of this class to your array.
class Stuff {}
var weakly : [Weak<Stuff>] = [Weak(value: Stuff()), Weak(value: Stuff())]
定义Weak
时,可以使用struct
或class
.
此外,为了帮助获取数组内容,您可以按照以下方式进行操作:
Also, to help with reaping array contents, you could do something along the lines of:
extension Array where Element:Weak<AnyObject> {
mutating func reap () {
self = self.filter { nil != $0.value }
}
}
上面的AnyObject
的使用应替换为T
-但我不认为当前的Swift语言允许这样定义扩展名.
The use of AnyObject
above should be replaced with T
- but I don't think the current Swift language allows an extension defined as such.
这篇关于如何在Swift中声明一个弱引用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文