Overriding a stored property in Swift

前端 未结 10 782
鱼传尺愫
鱼传尺愫 2020-11-30 00:10

I noticed that the compiler won\'t let me override a stored property with another stored value (which seems odd):

class Jedi {
    var lightSaberColor = \"Bl         


        
10条回答
  •  既然无缘
    2020-11-30 00:48

    Why am I not allowed to just give it another value?

    You are definitely allowed to give an inherited property a different value. You can do it if you initialize the property in a constructor that takes that initial value, and pass a different value from the derived class:

    class Jedi {
        // I made lightSaberColor read-only; you can make it writable if you prefer.
        let lightSaberColor : String
        init(_ lsc : String = "Blue") {
            lightSaberColor = lsc;
        }
    }
    
    class Sith : Jedi {
        init() {
            super.init("Red")
        }
    }
    
    let j1 = Jedi()
    let j2 = Sith()
    
    println(j1.lightSaberColor)
    println(j2.lightSaberColor)
    

    Overriding a property is not the same as giving it a new value - it is more like giving a class a different property. In fact, that is what happens when you override a computed property: the code that computes the property in the base class is replaced by code that computes the override for that property in the derived class.

    [Is it] possible to override the actual stored property, i.e. lightSaberColor that has some other behavior?

    Apart from observers, stored properties do not have behavior, so there is really nothing there to override. Giving the property a different value is possible through the mechanism described above. This does exactly what the example in the question is trying to achieve, with a different syntax.

提交回复
热议问题