46

How to declare static constant in class scope? such as

class let Constant: Double = 3.1415926
// I know that in class we use class modifier instead of static.
Zorayr
  • 22,104
  • 6
  • 124
  • 114
tounaobun
  • 14,042
  • 9
  • 49
  • 75

1 Answers1

117

Swift supports static type properties, including on classes, as of Swift 1.2:

class MyClass {
    static let pi = 3.1415926
}

If you need to have a class variable that is overridable in a subclass, you'll need to use a computed class property:

class MyClass {
    class var pi: Double { return 3.1415926 }
}

class IndianaClass : MyClass {
    override class var pi: Double { return 4 / (5 / 4) }
}
Nate Cook
  • 90,804
  • 32
  • 213
  • 175