Type Methods in Swift

Level 3215 keystrokes

static members belong to the type itself, so they are used without creating an instance. circleArea calls square and reads pi, and prints 78.53975 for radius 5.

Swift code

// A struct used only as a namespace for static members
1struct Math {
// Type constant shared by all uses, accessed as Math.pi
2 static let pi = 3.14159
3
// Type method: returns n squared
4 static func square(_ n: Double) -> Double {
5 return n * n
6 }
7
// Inside a static method, other static members can be used without the Math. prefix
8 static func circleArea(radius: Double) -> Double {
// Computes π × r²
9 return pi * square(radius)
10 }
11}
12
// Called on the type, no instance: 3.14159 × 25 = 78.53975
13print(Math.circleArea(radius: 5))

Output

78.53975
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 5
  • )× 5
  • :× 3
  • {× 3
  • }× 3
  • -× 2
  • .× 2
  • *× 2
  • >× 2
  • _× 1

More Swift examples at level 3

← Swift typing practice