overriding static vars in subclasses swift 1.2

后端 未结 4 1841
北海茫月
北海茫月 2021-01-07 16:58

unlike class var, where they can overridden in subclasses, I believe same applies to static as well but unfortunately not. Here\'s an example

相关标签:
4条回答
  • 2021-01-07 17:05

    As suggested, you cannot override static variables but can use class (static) function to override.

    class A {
       class func StaticValue() -> AnyObject {
          return "I am a String"
       }
    }
    
    class B: A {
        override class func StaticValue() -> AnyObject {
            return 2
        }
    }
    
    0 讨论(0)
  • 2021-01-07 17:06

    You can have computed class properties:

    public class A {
       class var NAME: String {
           return "A"
       }
    }
    
    public class B {
       class var NAME: String {
           return "B"
       }
    }
    

    If need be, you could even "branch" to a stored property in the subclass:

    public class A {
           // Needs to be overriden in subclass
           class var NAME: String {
               return "A"
           }
        }
    
    public class B {
       class var NAME: String {
           return B.storedName
       }
    
       static var storedName: String = defineName()
    
       func defineName() -> String {
           // You could do something more complex here
           return "B"
       }
    }
    
    0 讨论(0)
  • 2021-01-07 17:08

    You can use computed properties:

    class A {
       class var Name: String {
           return "A"
       }
    }
    
    class B: A {
       override class var Name: String {
           return "B"
       }
    }
    

    Usage:

    print(A.Name) // "A"
    print(B.Name) // "B"
    
    0 讨论(0)
  • 2021-01-07 17:28

    The documentation says:

    “ static ” methods and properties are now allowed in classes (as an alias for “ class final ”).

    So it is final, which means you cannot override it.

    0 讨论(0)
提交回复
热议问题