Static vs class functions/variables in Swift classes? Static vs class functions/variables in Swift classes? swift swift

Static vs class functions/variables in Swift classes?


static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

class properties will theoretically function in the same way (subclasses can override them), but they're not possible in Swift yet.


I tried mipadi's answer and comments on playground. And thought of sharing it. Here you go. I think mipadi's answer should be mark as accepted.

class A{    class func classFunction(){    }    static func staticFunction(){    }    class func classFunctionToBeMakeFinalInImmediateSubclass(){    }}class B: A {    override class func classFunction(){            }        //Compile Error. Class method overrides a 'final' class method    override static func staticFunction(){            }        //Let's avoid the function called 'classFunctionToBeMakeFinalInImmediateSubclass' being overriden by subclasses        /* First way of doing it    override static func classFunctionToBeMakeFinalInImmediateSubclass(){    }    */        // Second way of doing the same    override final class func classFunctionToBeMakeFinalInImmediateSubclass(){    }        //To use static or final class is choice of style.    //As mipadi suggests I would use. static at super class. and final class to cut off further overrides by a subclass}class C: B{    //Compile Error. Class method overrides a 'final' class method    override static func classFunctionToBeMakeFinalInImmediateSubclass(){            }}


Regarding to OOP, the answer is too simple:

The subclasses can override class methods, but cannot override static methods.

In addition to your post, if you want to declare a class variable (like you did class var myVar2 = ""), you should do it as follow:

class var myVar2: String {    return "whatever you want"}