Ios – How to override mutable property from a superclass

iosswift

class ArcaneCardVC: UIViewController {
    var currentCard: ArcaneCardView?
}

class PostVC: ArcaneCardVC {    
    override var currentCard: PostCard? 
// <===== This is what I want to do but cant
}

class ArcaneCardView: UIView {

}
class PostCard: ArcaneCardView {

}

Here is the error I get:

Cannot override mutable property 'currentCard' of type 'ArcaneCardView?' with covariant type 'PostCard?'

The other solution is explicitly doing this in code everytime I use currentCard:

var card = currentCard as! PostCard

Best Answer

When you override a variable, you can't change it's type. Why? Suppose that you are able to do that, then the following scenario would be possible:

var A: PostVC = PostVC() // some initialization 
var B: ArcaneCardVC = A // this is a valid state since `PostVC` is a subclass of `ArcaneCardVC`

What should be the type of B.currentCard? Hmm, this is a complicated question. You can answer that its type should be PostCard. Ok, lets add other classes to the party:

class OtherCard: ArcaneCardView {

}

class OtherVC: ArcaneCardVC {    
    override var currentCard: OtherCard?      
}

Considerer now the following code:

var A: ArcaneCardVC = PostVC()
var B: ArcaneCardVC = OtherVC()
A.currentCard = B.currentCard // something will crash here!!!

For avoiding this kind of behavior, you can't change the type of a property when you are subclassing.