Swift - Custom Type Type Methods

Introduction

Type methods are methods that belong to the class.

Type methods are called directly using the class name, not through instances of the class.

In Swift, structures, classes, and enumerations support type methods.

Type methods are declared similarly to instance methods, except that they are prefixed with the class keyword.

The following code shows that the Truck class has the class method named kilometersToMiles() :


class Truck {
    var speed = 0
    class func kilometersToMiles(km:Int) -> Double{
        return Double(km) / 1.60934
    }

    ...
}

To use the kilometersToMiles() method, use the class name and call the method directly:

c.speed = 30
var s = Truck.kilometersToMiles(c.speed)
print("\(s) mph")    //18.6411820994942 mph

Class methods are often used for utility functions, where implementation is independent of each instance of the class.

Related Topic