How do I declare an array of weak references in Swift?
Create a generic wrapper as:
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())]
When defining Weak
you can use either struct
or 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 }
}
}
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.
A functional programming approach
No extra class needed.
Simply define an array of closures () -> Foo?
and capture the foo instance as weak using [weak foo]
.
let foo = Foo()
var foos = [() -> Foo?]()
foos.append({ [weak foo] in return foo })
foos.forEach { $0()?.doSomething() }
You can use the NSHashTable with weakObjectsHashTable. NSHashTable<ObjectType>.weakObjectsHashTable()
For Swift 3: NSHashTable<ObjectType>.weakObjects()
NSHashTable Class Reference
Available in OS X v10.5 and later.
Available in iOS 6.0 and later.