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 source
1extension Int {
// Computed property: self is the integer itself
2 var squared: Int { return self * self }
// Takes a closure with no arguments and no return value
3 func times(_ action: () -> Void) {
// Calls the closure self times; _ ignores the loop counter
4 for _ in 0..<self { action() }
5 }
6}
7
// Literals can use the new members directly: prints 5 squared: 25
8print("5 squared: \(5.squared)")
// Trailing closure syntax; prints Hello! three times
93.times { print("Hello!") }

Output

5 squared: 25
Hello!
Hello!
Hello!
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.

  • (× 6
  • )× 6
  • {× 5
  • }× 5
  • .× 4
  • "× 4
  • :× 3
  • _× 2
  • -× 1
  • !× 1

More Swift examples at level 4

← Swift typing practice