For the More Curious: Type Methods

In this chapter, you defined some instance methods that were called on instances of a type. For example, terrorizeTown() is an instance method that you can call on instances of the Monster type. You can additionally define methods that are called on the type itself. These are called type methods. Type methods are useful for working with type-level information.

Imagine a struct named Square:

struct Square {
    static func numberOfSides() -> Int {
        return 4
    }
}

For value types, you indicate that you are defining a type method with the static keyword. The method numberOfSides() simply returns the number of sides a Square can have.

In distinction, type methods on classes use the class keyword. Here ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.