1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Emil Adz
  • 40,709
  • 36
  • 140
  • 187
  • Did you check this: : http://stackoverflow.com/questions/26156561/xcode-6-0-1-command-applications-xcode-app-contents-developer-toolchains-xcoded – Jaycee Aug 04 '15 at 11:35
  • Yes, I did now... But my problem is not related to the solution there, They are saying to change the release Optimization Level, I get this problem in debug. moreover changing this settings does not do me any good. – Emil Adz Aug 04 '15 at 12:18

2 Answers2

0

You could use NSHashTable.weakObjectsHashTable() instead of the build-in Swift dictionary.

Wolfgang Schreurs
  • 11,779
  • 7
  • 51
  • 92
0

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.

Howard Lovatt
  • 968
  • 1
  • 8
  • 15