Type methods

Like type properties, you can use type methods to access data across all instances. You call type methods on the type itself, instead of on an instance. To define a type method, you prefix it with the static modifier.

Type methods are useful for things that are about a type in general, rather than something about specific instances.

For example, you could use type methods to group similar methods into a structure:

struct Math {

// 1

static func factorial(of number: Int) -> Int {

// 2

return (1...number).reduce(1, *)

}

}

// 3

let factorial = Math.factorial(of: 6) // 720

You might have custom calculations for things such as factorial. Instead of having a bunch of free standing functions, you can group related functions together as type methods in a structure. The structure is said act as a namespace.

Here’s what’s happening:

  1. You use static to declare the type method, which accepts an integer and returns an integer.
  2. The implementation uses a higher-order function called reduce(::). It effectively follows the formula for calculating a factorial: “The product of all the whole numbers from 1 to n”. You could write this using a for loop, but the higher-order function expresses your intent in a cleaner way.
  3. You call the type method on Math, rather than on an instance of the type.

Type methods gathered into a structure code complete well. In this example, you can see all the math utility methods available to you by typing Math..

results matching ""

    No results matching ""