47

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
  • 23,770
  • 8
  • 136
  • 129
tounaobun
  • 14,570
  • 9
  • 53
  • 75

1 Answers1

118

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
  • 92,417
  • 32
  • 217
  • 178
  • 2
    Is global variable available in other classes as well?(In the same module) – tounaobun Nov 07 '14 at 15:40
  • 1
    Yes, so long as they aren't marked `private`, they'll be available in any class in your module. – Nate Cook Nov 07 '14 at 15:41
  • So in the xcodeproj,is it best practice to create a constant.swift file to include all the constants?(Unlike java,we do not need to create a new class) – tounaobun Nov 07 '14 at 16:10
  • Well, there aren't truly *best practices* yet, though there are lots of different ideas of what they should be. If a single file with all your constants makes the most sense for your project, go for it - that'd be roughly analogous to a "Constants.h" file in an Objective-C project. – Nate Cook Nov 07 '14 at 16:16
  • 1
    As of Swift 1.2, static variables are also available - http://swiftdoc.org/type/Process/ . – marius bardan Feb 18 '15 at 18:55
  • @marius looks like only in `enums` though... – Sumner Evans Mar 26 '15 at 13:59
  • I see what you did there :-) – almas Oct 19 '15 at 00:42
  • So here, are the "class var" declarations simply declarations of a subclass of MyClass which consists entirely of one variable ? What exactly is "class var" ? – Jack Berstrem Feb 29 '16 at 18:19
  • 4
    Kudos for referencing the [Indiana Pi Bill](https://en.wikipedia.org/wiki/Indiana_Pi_Bill) – pr1001 Apr 05 '16 at 14:49