0

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?

Patia1999
  • 67
  • 1
  • 7
  • 2
    This is caused by the fact that [generic types in Swift are invariant](https://stackoverflow.com/questions/41976844/swift-generic-coercion-misunderstanding). This means that `S` and `S` are completely unrelated types. Why do you need `S` to be generic? Couldn't you simply use the base-class, `UIView` for your generic parameters/properties in `S` instead? – Dávid Pásztor Feb 25 '20 at 10:32
  • I see. Interesting post. Thank you. I can’t use `UIView` if I want to store properties; these don’t go into extensions. – Patia1999 Feb 25 '20 at 11:43

0 Answers0