Search code examples
inheritanceswiftpropertiesoverridingivar

Swift computed properties in Swift with instance variable?


I'm trying to create a computed property in Swift and I need an instance variable to save the state of the property.

This happens specially when I'm trying to override a property in my superclass:

class Jedi {
    var lightSaberColor = "Blue"
}


class Sith: Jedi {
    var _color = "Red"
    override var lightSaberColor : String{
        get{
            return _color
        }
        set{
            _color = newValue
        }
    }

}

I'm overriding the stored property lightSaberColor in Jedi with a computed property because that's the only way the compiler will let me. It also forces me to create a getter and setter (which makes sense). And that's when I run into trouble.

So far, the only way I've found is to define this extra and ugly var _color. Is thee a more elegant solution?

I tried defining _color inside the property block, but it won't compile.

There's gotta be a better way!


Solution

  • The way you have it is the only way it can work right now - the only change I would make is to declare _color as private.

    Depending on your needs, it may be enough to have a stored property with willGet and/or didSet handlers.