Fast computed properties in Swift with instance variable?

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

This happens on purpose when I try 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 am overriding the persisted lightSaberColor property in Jedi with a computed property because that is the only way the compiler will let me. It also forces me to create a getter and a setter (which makes sense). And this is when I ran into trouble.

So far, the only way I've found is to define this redundant and ugly var _color

. Is there a more elegant solution?

I tried to define _color

inside the properties block, but it won't compile.

There must be a better way!

+3


source to share


2 answers


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

as private

.



Depending on your needs, it may be sufficient to have a stored property with handlers willGet

and / or didSet

.

+5


source


Why not just set it in the initializer?



class Jedi {
    var lightSaberColor = "Blue"
}

class Sith: Jedi {
    override init () {
        super.init()
        self.lightSaberColor = "Red"
    }
}

      

+3


source







All Articles