Tuesday, September 19, 2017

Swift - Class and Static Methods

Both the static and class methods can only be accessed with class as they are not Instance methods.

---------------------------------------------------------------------------------------------------------

class Methods {
    func publicMethod() {
        print("Methods - publicMethod")
    }
    class func classMethod() {
         print("Methods - classMthod")
    }
    static func staticMethod() {
        print("Methods - staticMethod")
    }
}

let methods = Methods()  

methods.publicMethod()  // accessed using instance

Methods.staticMethod() // accessed using class
Methods.classMethod()  // accessed using class

----------------------------
-----------------------------------------------------------------------------

The only difference between static and class methods is, Class methods can be overridden but not static methods. Overriding static methods will result in a compile time error.

----------------------------
-----------------------------------------------------------------------------

class SubClassMethods: Methods {
    override func publicMethod() {
        print("SubClassMethods - publicMethod")
    }
    override class func classMethod() {
        print("SubClassMethods - classMethod")
    }
    override static func staticMethod() {   // Can not override static method
        print("Methods - staticMethod")
    }
}

----------------------------
--------------------------------------------------------
---------------------

Note: Structures can have static methods, They can not have class methods.


Hope this post is useful. Feel free to comment incase of any queries.


No comments:

Post a Comment