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!
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.
Why not just set it in initializer?
class Jedi {
var lightSaberColor = "Blue"
}
class Sith: Jedi {
override init () {
super.init()
self.lightSaberColor = "Red"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With