4

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!

cfischer
  • 24,452
  • 37
  • 131
  • 214

2 Answers2

5

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.

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
3

Why not just set it in initializer?

class Jedi {
    var lightSaberColor = "Blue"
}

class Sith: Jedi {
    override init () {
        super.init()
        self.lightSaberColor = "Red"
    }
}
Shuo
  • 8,447
  • 4
  • 30
  • 36