我使用Swift 2和使用WeakContainer作为一种方式来存储一组弱对象,很像NSHashTable.weakObjectsHashTable()
struct WeakContainer<T: AnyObject> { weak var value: T? } public protocol MyDelegate : AnyObject { }
然后在我的ViewController,我声明
public var delegates = [WeakContainer<MyDelegate>]
但它是错误
Using MyDelegate as a concrete type conforming to protocol AnyObject is not supported
我看到的错误是WeakContainer有值成员声明为弱,所以T期望是对象。但我也声明MyDelegate为AnyObject。如何解决这个问题?
我有同样的想法创建弱集装箱与泛型。
作为结果,我创建了NSHashTable包装,并为您的编译器错误做了一些解决方法。
原文链接:https://www.f2er.com/swift/320780.html作为结果,我创建了NSHashTable包装,并为您的编译器错误做了一些解决方法。
class WeakSet<ObjectType>: SequenceType { var count: Int { return weakStorage.count } private let weakStorage = NSHashTable.weakObjectsHashTable() func addObject(object: ObjectType) { guard object is AnyObject else { fatalError("Object (\(object)) should be subclass of AnyObject") } weakStorage.addObject(object as? AnyObject) } func removeObject(object: ObjectType) { guard object is AnyObject else { fatalError("Object (\(object)) should be subclass of AnyObject") } weakStorage.removeObject(object as? AnyObject) } func removeAllObjects() { weakStorage.removeAllObjects() } func containsObject(object: ObjectType) -> Bool { guard object is AnyObject else { fatalError("Object (\(object)) should be subclass of AnyObject") } return weakStorage.containsObject(object as? AnyObject) } func generate() -> AnyGenerator<ObjectType> { let enumerator = weakStorage.objectEnumerator() return anyGenerator { return enumerator.nextObject() as! ObjectType? } } }
用法:
protocol MyDelegate : AnyObject { func doWork() } class MyClass: AnyObject,MyDelegate { fun doWork() { // Do delegated work. } } var delegates = WeakSet<MyDelegate>() delegates.addObject(MyClass()) for delegate in delegates { delegate.doWork() }
这不是最好的解决方案,因为WeakSet可以用任何类型的初始化,如果这种类型不符合AnyObject协议,那么应用程序将崩溃。但我现在没有看到任何更好的解决方案。