lucab
(Luca Bartoletti)
1
I'm trying to develop an extension of UIView that would allow me to have a support class
extension UIView {
var support: Support {
// setup associated object if necessary
}
}
I'm doing this as an extension to UIView because it needs to be available on all UIView and subclasses.
The problem I found is that Support needs to know about the concrete type of the UIView
So it would be obvious to make Support generic but that doesn't work in the extensions because you can't have
extension UIView {
var support: Support<Self> {
// setup associated object if necessary
}
}
Is there a way to achieve something that would allow me to have
let view = UIView()
let someView = SomeView() // : `UIView`
view.support // Returns `Support<UIView>`
someView.support // Returns `Support<SomeView>`
I don’t believe this is possible, since generic types are generally invariant in Swift. Consider the following:
func operateOnBareUIViewSupport(_ s: Support<UIView>) {}
let view = SomeView()
operateOnBareUIViewSupport(view.support) // not allowed
let theSameView: UIView = view
operateOnBareUIViewSupport(theSameView.support) // okay
The correct way to handle this would be to make it a static method:
struct Support<T: UIView> {
static func support(for view: T) -> Support<T> {
// ...
}
}
operateOnBareUIViewSupport(.support(for: SomeView())) // okay
tera
3
What exactly is Support ?