Overriding a stored property in Swift

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

    For Swift 4, from Apple's documentation:

    You can override an inherited instance or type property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.

    0 讨论(0)
  • 2020-11-30 00:50
    class SomeClass {
        var hello = "hello"
    }
    class ChildClass: SomeClass {
        override var hello: String {
            set {
                super.hello = newValue
            }
            get {
                return super.hello
            }    
        }
    }
    
    0 讨论(0)
  • 2020-11-30 00:56

    You probably want to assing another value to the property:

    class Jedi {
        var lightSaberColor = "Blue"
    }
    
    
    class Sith: Jedi {
        override init() {
            super.init()
            self.lightSaberColor = "Red"
        }
    }
    
    0 讨论(0)
  • 2020-11-30 00:56

    I had the same problem to set a constant for a view controller.

    As I'm using interface builder to manage the view, I cannot use init(), so my workaround was similar to other answers, except I used a read-only computed variable on both base and inherited classes.

    class Jedi {
        var type: String {
            get { return "Blue" }
        }
    }
    
    class Sith: Jedi {
        override var type: String {
            get { return "Red" }
        }
    }
    
    0 讨论(0)
提交回复
热议问题