Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 523
cfischer Avatar asked Feb 11 '23 16:02

cfischer


2 Answers

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.

like image 161
Nate Cook Avatar answered Mar 07 '23 05:03

Nate Cook


Why not just set it in initializer?

class Jedi {
    var lightSaberColor = "Blue"
}

class Sith: Jedi {
    override init () {
        super.init()
        self.lightSaberColor = "Red"
    }
}
like image 42
Shuo Avatar answered Mar 07 '23 06:03

Shuo