8 Replies
      Latest reply on May 24, 2018 6:19 PM by 0xfeedface
      0xfeedface Level 1 Level 1 (0 points)

        I have try to override variable in subclass many times, but never try override getter/setter before today, this is my Swift code in Playground :

         

        class Person {
            var name: String {
                didSet {
                    print("Superclass did Set")
                }
                willSet {
                    print("Superclass will Set")
                }
            }
            init(name: String) {
                self.name = name
            }
        }
        
        class Student: Person {
            override var name: String {
                didSet {
                    print("Subclass did Set")
                }
                willSet {
                    print("Subclass will Set")
                }
            }
        }
        
        let apple = Student(name: "John")
        apple.name = "Apple"

         

        The results like below:

         

        Subclass will Set

        Superclass will Set

        Superclass did Set

        Subclass did Set

         

        That's mean we can't override variable setter/getter?

        • Re: Override getter/setter problem
          Claude31 Level 7 Level 7 (4,935 points)

          Looks like you have to define as a class var

          see h ttps://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

           

          For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation. The example below shows the syntax for stored and computed type properties:

           

          Also found an interesting discussion here:

          h ttps://stackoverflow.com/questions/29971528/overriding-getter-in-swift

           

          Hope that helps.