Overriding a stored property in Swift

前端 未结 10 815
鱼传尺愫
鱼传尺愫 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:33

    For me, your example does not work in Swift 3.0.1.

    I entered in the playground this code:

    class Jedi {
        let lightsaberColor = "Blue"
    }
    
    class Sith: Jedi {
        override var lightsaberColor : String {
            return "Red"
        }
    }
    

    Throws error at compile time in Xcode:

    cannot override immutable 'let' property 'lightsaberColor' with the getter of a 'var'

    No, you can not change the type of stored property. The Liskov Substitution Principle forces you to allow that a subclass is used in a place where the superclass is wanted.

    But if you change it to var and therefore add the set in the computed property, you can override the stored property with a computed property of the same type.

    class Jedi {
        var lightsaberColor = "Blue"
    }
    
    
    class Sith: Jedi {
        override var lightsaberColor : String {
            get {
                return "Red"
            }
            set {
                // nothing, because only red is allowed
            }
        }
    }
    

    This is possible because it can make sense to switch from stored property to computed property.

    But override a stored var property with a stored var property does not make sense, because you can only change the value of the property.

    You can, however, not override a stored property with a stored property at all.


    I would not say Sith are Jedi :-P. Therefore it is clear that this can not work.

提交回复
热议问题