Closure Expressions in Swift

Level 3148 keystrokes

Defines two closures, one whose type comes from an annotation and one with types written inside the closure, and calls them like functions: prints 7 and 30.

Swift code

// The annotation (Int, Int) -> Int lets Swift infer the types of a and b
1let add: (Int, Int) -> Int = { (a, b) in
// in separates the parameters from the body; return gives the sum
2 return a + b
3}
4
// Types written in the closure; a single expression is returned without return
5let multiply = { (a: Int, b: Int) -> Int in a * b }
6
// Closures are called like functions: 3 + 4 = 7
7print(add(3, 4))
// 5 * 6 = 30
8print(multiply(5, 6))

Output

7
30
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.

  • (× 7
  • )× 7
  • ,× 5
  • :× 3
  • -× 2
  • {× 2
  • }× 2
  • =× 2
  • >× 2
  • *× 1

More Swift examples at level 3

← Swift typing practice