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