I’d like to create an array of different objects of the same generic class:
import UIKit
struct S<V: UIView> {}
let a: [S<UIView>] = [S<UIButton>(), S<UILabel>()]
Cannot convert value of type 'S<UIButton>' to expected element type 'S<UIView>'
Cannot convert value of type 'S<UILabel>' to expected element type 'S<UIView>'
The only workaround I could come up with is a protocol wrapper:
import UIKit
protocol P {}
struct S<V: UIView>: P {}
let a: [P] = [S<UIButton>(), S<UILabel>()]
I don’t really feel like it is necessary to redefine all of S
’s properties and methods in P
. Are there any other solutions out there?
EDIT:
With this workaround one would also run into the problem of needing a assotiated type in the protocol:
import UIKit
protocol P {
associatedtype V: UIView
}
struct S<V: UIView>: P {}
let a: [P] = [S<UIButton>(), S<UILabel>()]
Protocol 'P' can only be used as a generic constraint because it has Self or associated type requirements
How would I solve this?