I am trying to create an array of weak references to objects that support a certain protocol. Below, the WeakBox and WeakArray are from https://www.objc.io/blog/2017/12/28/weak-arrays/.
The function testingWeakStuff manage to create a weak array of objects (arr1) and an ordinary array of references to the protocol (arr3) but it fails to create arr2. The compiler does not deduce that MyProtocol is of class type.
How to fix this problem?
final class WeakBox<A: AnyObject> {
weak var unbox: A?
init(_ value: A) {
unbox = value
}
}
struct WeakArray<T: AnyObject> {
private var items: [WeakBox<T>] = []
init(){
}
init(_ elements: [T]) {
items = elements.map { WeakBox($0) }
}
}
protocol MyProtocol : AnyObject {
func f();
}
class AClass : MyProtocol {
func f() {
print("Hello, world!")
}
}
func testingWeakStuff(){
var arr1 = WeakArray<AClass>()
var arr2 = WeakArray<MyProtocol>() // 'WeakArray' requires that 'any MyProtocol' be a class type
var arr3 = [MyProtocol]()
}