Compact Map in Swift

Level 3204 keystrokes

compactMap transforms each element and drops the nil results in one step. It keeps only the strings that convert to Int, then only the elements that cast to Int, printing [1, 3, 5] and [1, 3].

Swift code

// Some strings are numbers, some are words
1let strings = ["1", "two", "3", "four", "5"]
// Int($0) returns Int?; nil for "two" and "four", which compactMap drops
2let numbers = strings.compactMap { Int($0) }
// Prints [1, 3, 5]
3print(numbers)
4
// [Any] can hold values of different types
5let mixed: [Any] = [1, "hello", 3, "world"]
// as? Int gives nil for the strings, so only the integers remain
6let ints = mixed.compactMap { $0 as? Int }
// Prints [1, 3]
7print(ints)

Output

[1, 3, 5]
[1, 3]
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.

  • "× 14
  • ,× 7
  • =× 4
  • (× 3
  • )× 3
  • [× 3
  • ]× 3
  • .× 2
  • {× 2
  • }× 2

More Swift examples at level 3

← Swift typing practice