Background
Let's consider the following working code
protocol CanFly { }
protocol Container {
associatedtype ContentType
var value: ContentType? { get }
}
class Box<V>: Container {
var value: V?
}
let box = Box<CanFly>()
box.value // <- has type `CanFly?`
Here
Box
accepts a protocol as generic type, beautiful isn't it?
Things get harder
Now I want to do a "small" change, I make the value
property in Box weak
class Box<V>: Container {
weak var value: V?
}
And of course I get this error
class Box<V>: Container {
weak var value: V? // 'weak' must not be applied to non-class-bound 'V'; consider adding a protocol conformance that has a class bound
}
I try to fix it constraining V
to be an AnyObject
class Box<V:AnyObject>: Container {
weak var value: V?
}
And I get this error
let box = Box<CanFly>() // 'Box' requires that 'CanFly' be a class type
The problem
The problem here is that since I defined V:AnyObject
I can no longer use the protocol CanFly
as generic type of Box
.
The question
I want
- to be able to use a protocol as generic type of Box
- AND the
Box#value
property to beweak
How can I do that?
Final considerations
I am looking for something like this
class Box<V:ProtocolForClassOnly>: Container {
weak var value: V?
}
P.S. The closest question on StackOverflow I could find is this one but unfortunately hasn't helped me.