overriding static vars in subclasses swift 1.2

后端 未结 4 1842
北海茫月
北海茫月 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: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"
       }
    }
    

提交回复
热议问题