Overriding a stored property in Swift

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

    If you attempt to do that in Swift 5 you will be greeted by a

    Cannot override immutable 'let' property 'lightSaberColor' with the getter of a 'var'

    Your best bet is to declare it as a computed property.

    This works as we are just overriding the get {} function

    class Base {
       var lightSaberColor: String { "base" }
    }
    
    class Red: Base {
       override var lightSaberColor: String { "red" }
    }
    

提交回复
热议问题