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 members1struct Math { // Type constant shared by all uses, accessed as Math.pi2 static let pi = 3.141593 // Type method: returns n squared4 static func square(_ n: Double) -> Double {5 return n * n6 }7 // Inside a static method, other static members can be used without the Math. prefix8 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.5397513print(Math.circleArea(radius: 5))Output
78.53975
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