0

I have a class Superclass with generic type UIView. The class Subclass inherits from Superclass:

class Superclass<T: UIView>: UIViewController { ... }

class Subclass: Superclass<UIButton> { ... }

And now, from another UIViewController I am trying to initialise an object of type Subclass like this:

let childViewController: Superclass<UIView>?
    switch type {
    case .typeOne:
      childViewController = Subclass()
    default:
      childViewController = nil
    }

But is is throwing the following error:

Cannot assign value of type 'Subclass' to type 'Superclass<UIView>?'

How can I specify that I want to initialise the childViewController with a UIButton type, for example?

Thanks!

anonymous
  • 1,320
  • 5
  • 21
  • 37

1 Answers1

1

If you want to create an object of Superclass, you initiate it like,

    let parentViewController: Superclass<UIButton>? = Superclass<UIButton>()

i.e. you need to use the same Type for Generic while instantiating the object, as you have used while defining the variable.

Similarly, the Subclass is of type Superclass<UIButton> and not Superclass<UIView>.

So, you need to define childViewController with the same Generic type, that the Subclass accepts, i.e.

    let childViewController: Superclass<UIButton>?
    switch type {
    case .typeOne:
        childViewController = Subclass()
    default:
        childViewController = nil
    }
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • Yes, I already got that working, but the thing is that I have a `switch case` that depending on the value, I want to initialise that `Subclass` class with different types of `UIView`. How can I achieve that? – anonymous Oct 23 '17 at 08:33