rollingcodes
rollingcodes

Reputation: 16038

Swift: Override Subclass Properties that are also Subclasses of the Parent Class Property Class

Seems like a confusing question to word but it's actually pretty simple. I want to do something like this but Swift won't allow it:

class A {}
class B : A {}
class C {
    var prop: A?
}
class D : C {
    override var prop : B?
}

Upvotes: 4

Views: 1620

Answers (2)

Kartick Vaddadi
Kartick Vaddadi

Reputation: 4998

There's no sensible way to do what you're asking, which is covariance/contravariance. Imagine this code:

func storeProperty(_ c: C) {
  c.prop = A()
}

let d = D()
storeProperty(d)
let b: B = d.prop

If your idea were to work, we have a type error — a variable of type B that doesn't contain a B at runtime!

Upvotes: 0

Evdzhan Mustafa
Evdzhan Mustafa

Reputation: 3735

Taken from here:

Overriding Property Getters and Setters

You can provide a custom getter (and setter, if appropriate) to override any inherited property, regardless of whether the inherited property is implemented as a stored or computed property at source. The stored or computed nature of an inherited property is not known by a subclass—it only knows that the inherited property has a certain name and type. You must always state both the name and the type of the property you are overriding, to enable the compiler to check that your override matches a superclass property with the same name and type.

Seems like you cant do that.

Upvotes: 4

Related Questions