32

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

public class A {
    private static let NAME: String = "A"
}

public class B: A {
    private static let NAME: String = "B" //error
}

in my opinion static means association with that particular class, so in the above example B should get it's own space to redefine that variable as it's associated to B only, I'm reverting to stored properties unless someone has a better solution.

4 Answers4

38

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"
gdub
  • 793
  • 9
  • 16
31

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.

Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
18

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
    }
}
Antonioni
  • 578
  • 1
  • 5
  • 15
Nivash
  • 305
  • 1
  • 3
  • 5
3

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"
   }
}
Frederic Adda
  • 5,905
  • 4
  • 56
  • 71
  • 2
    Excellent hints. Just a few remarks - I believe your intention was `public class B: A` not `public class B`. Also you have to add `override` keyword `override class var name: String`. Not fully understand your intention with `static var storedName: String = defineName()`, because you can't use instance method to initialize static/class properties. – Mikolaj Jul 24 '16 at 15:12