0

I want to have a property in BaseClass which is an array of type anything which extends Movable and in subclass I want to override the same property with type Transportable which extends Movable.

How do we declare "anything which extends Movable" in Swift?

protocol Movable{
    func move()
}

struct Transportable : Movable{
    func transport()
}

class BaseClass{
    var myProperty: [Movable] = []
}

class MyClass: BaseClass{
    override var myProperty = [Transportable]()
}

It doesn't compile and gives me an error:

Property 'myProperty' with type '[Transportable]' cannot override a property with type '[Movable]'

FE_Tech
  • 1,534
  • 13
  • 25
  • 2
    Does this answer your question? [Overriding superclass property with different type in Swift](https://stackoverflow.com/questions/24094158/overriding-superclass-property-with-different-type-in-swift) – Keshu R. Dec 10 '19 at 09:57
  • Better to use generics here – Joakim Danielson Dec 10 '19 at 10:01
  • @JoakimDanielson I am new to generics. Can you please show me how generics will solve this? – FE_Tech Dec 10 '19 at 10:06
  • Define the base class as `class BaseClass{ var myProperty: [T] = [] }` and then remove the property from the sub class and change the definition of it to `class MyClass: BaseClass` – Joakim Danielson Dec 10 '19 at 10:11

0 Answers0