I know that static
keyword is used to declare type variable/method in struct
, enum
etc.
But today I found it can also be used in class
entity.
class foo {
static func hi() {
println("hi")
}
class func hello() {
println("hello")
}
}
What's static
keyword's use in class
entity?
Thanks!
edit: I'm referring to Swift 1.2 if that makes any difference
The main difference is static is for static functions of structs and enums, and class for classes and protocols. From Chris Lattner the father of Swift. We considered unifying the syntax (e.g. using “type” as the keyword), but that doesn't actually simply things.
Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.
The static property defines a "type property", one that is instantiated once and only once. As you note, this happens lazily, as statics behave like globals. And as The Swift Programming Language: Properties says: Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties.
You create static variable by appending static keyword in front of your variable declaration. We will be using playground to explore more. When we define any variable as let, it means it's values cannot be modified, On the other hand if we define any variable as var it means it's values can be modified.
From the Xcode 3 beta 3 release notes:
“static” methods and properties are now allowed in classes (as an alias for “class final”).
So in Swift 1.2, hi()
defined as
class foo {
static func hi() {
println("hi")
}
}
is a type method (i.e. a method that is called on the type itself) which also is final (i.e. cannot be overridden in a subclass).
In classes it's used for exactly the same purpose. However before Swift 1.2 (currently in beta) static
was not available - the alternate class
specifier was been made available for declaring static methods and computed properties, but not stored properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With