简体   繁体   中英

How to create a dictionary of weak references in Swift?

I need to store delegates which are views in a dictionary. Now I want to hold them as weak references, So if the user quits the screen my dictionary won't be the one preventing those views to cleanup.

I was trying to use the solution from:

How do I declare an array of weak references in Swift?

But for some reason as soon as I add the line of code where I try to get the real delegate from the weak object:

if let realDelegate = delegate.value {
    realDelegate.updateProgressBar(Int(progress * 100), aTaskIndentifier: downloadTask.taskIdentifier)
}

I get the following error in Xcode at compile time:

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Do you know what is the problem with this solution? Or maybe you could provide another solutions for this task?

您可以使用NSHashTable.weakObjectsHashTable()代替内置的Swift字典。

Following works for me:

struct WeakReference<T: AnyObject> {
    weak var value: T?
}
@objc protocol P { // Note @objc, class or AnyObject does not work
    var i: Int { get }
}
class CP: P {
    var i: Int = 0
}
let cP = CP() // Strong reference to prevent collection
let weakPD: [Int : WeakReference<P>] = [0 : WeakReference(value: cP)]
print("PD: \(weakPD[0]!.value!.i)") // 0

But note I had to use @objc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM