Static vs class functions/variables in Swift classes?
Asked 07 September, 2021
Viewed 2K times
  • 71
Votes

The following code compiles in Swift 1.2:

class myClass {
    static func myMethod1() {
    }
    class func myMethod2() {
    }
    static var myVar1 = ""
}

func doSomething() {
    myClass.myMethod1()
    myClass.myMethod2()
    myClass.myVar1 = "abc"
}

What is the difference between a static function and a class function? Which one should I use, and when?

If I try to define another variable class var myVar2 = "", it says:


  

Class stored properties not yet supported in classes; did you mean 'static'?

When this feature is supported, what will the difference be between a static variable and a class variable (i.e. when both are defined in a class)? Which one should I use, and when?

(Xcode 6.3)

9 Answer