问题描述
我使用 Swift 2 并使用 WeakContainer 作为存储一组弱对象的方式,很像 NSHashTable.weakObjectsHashTable()
I'm using Swift 2 and using WeakContainer as a way to store a set of weak objects, much like NSHashTable.weakObjectsHashTable()
struct WeakContainer<T: AnyObject> {
weak var value: T?
}
public protocol MyDelegate : AnyObject {
}
然后在我的 ViewController 中,我声明
Then in my ViewController, I declare
public var delegates = [WeakContainer<MyDelegate>]
这是错误的
不支持使用 MyDelegate 作为符合 AnyObject 协议的具体类型
我看到错误是 WeakContainer
有 value
成员声明为 weak
,所以 T
是预期的成为对象.但我也将 MyDelegate
声明为 AnyObject
.如何解决这个问题?
I see that the error is that WeakContainer
has value
member declared as weak
, so T
is expected to be object. But I also declare MyDelegate
as AnyObject
, too. How to get around this?
推荐答案
我有同样的想法,用泛型创建弱容器.
因此,我为 NSHashTable
创建了包装器,并为您的编译器错误做了一些解决方法.
I had the same idea to create weak container with generics.
As result I created wrapper for NSHashTable
and did some workaround for your compiler error.
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
协议,那么应用程序就会崩溃.但我现在看不到更好的解决方案.
It's not the best solution, because WeakSet
can be initialized with any type, and if this type doesn't conform to AnyObject
protocol then app will crash. But I don't see any better solution right now.
这篇关于不支持用作符合协议 AnyObject 的具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!