Type Extension in Swift
Level 4187 keystrokes
An extension adds a computed property squared and a method times to the built-in Int type. It prints 5 squared: 25 and then Hello! three times.
Swift code
// Adds members to the existing Int type without changing its source1extension Int { // Computed property: self is the integer itself2 var squared: Int { return self * self } // Takes a closure with no arguments and no return value3 func times(_ action: () -> Void) { // Calls the closure self times; _ ignores the loop counter4 for _ in 0..<self { action() }5 }6}7 // Literals can use the new members directly: prints 5 squared: 258print("5 squared: \(5.squared)")// Trailing closure syntax; prints Hello! three times93.times { print("Hello!") }Output
5 squared: 25 Hello! Hello! Hello!
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.
(× 6)× 6{× 5}× 5.× 4"× 4:× 3_× 2-× 1!× 1