O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required