Reputation:
In Java I can create a static initializer like:
static { ... }
In Swift I can have:
class MyClass {
class var myVar:Int?
}
Is it possible to create some kind of class/static var initializer in Swift?
Upvotes: 10
Views: 5467
Reputation: 11683
If you need a computed property accessible from the class type and you want it to be like a constant value, the best option is static
keyword.
Type Property Syntax
“For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/pt/jEUH0.l
With class
keyword a subclass can override the computed value.
Best solution:
class MyClass {
static var myVar: Int {
return 0
}
}
Upvotes: 5