Object Oriented Programming

Type Methods in Swift

Type methods are methods that are called on the class itself, not on a specific object instance. The static modifier ensures implementation is the same across all class instances.

Equivalent to class methods and static methods in other languages.


Syntax
public class className {
    modifier static dataType methodName (inputParameters) -> returnDataType { //static method
         //block of code to be executed
    }
}

//calling the method, from anywhere
className.methodName(passedParams);

Notes

The 'class' keyword can be used in place of the 'static' keyword to allow subclass overriding of the type method.

Methods tied to class objects are known as instance methods. They are declared like regular functions.


Example
public class Numbers {
    static func findMinimum(number1: Int, number2: Int) -> Int { 
        //3 stored in number1, 5 stored in number2
        var minimum: Int = number2
        if number1 < number2 {
            minimum = number1
        }
        return minimum 
    }
}

var min = Numbers.findMinimum(number1: 3, number2: 5)

< Instantiation   |   Properties >

© 2019 SyntaxDB. All Rights Reserved.