Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static vs class as class variable/method (Swift)

Tags:

ios

swift

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

like image 685
Daniel Shin Avatar asked Mar 23 '15 09:03

Daniel Shin


People also ask

What is difference between static and class method in Swift?

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.

Are class variables and static variables the same?

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.

Are static variables lazy Swift?

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.

What is difference between static let and static VAR in Swift?

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.


2 Answers

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).

like image 167
Martin R Avatar answered Sep 21 '22 14:09

Martin R


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.

like image 34
Antonio Avatar answered Sep 21 '22 14:09

Antonio