Reduce Operation in Swift
Level 5519 keystrokes
reduce combines all elements into one value, starting from an initial value. Here it computes a sum, a product, a sentence, and a tuple with the minimum, maximum and sum in a single pass.
Swift code
1let numbers = [1, 2, 3, 4, 5]2 // Starts at 0 and adds each number: 153let sum = numbers.reduce(0) { $0 + $1 }// The * operator itself is passed as the combining function: 1204let product = numbers.reduce(1, *)5 6let words = ["Swift", "is", "awesome"]// Avoids a leading space: the first word is used as is, later ones get a space7let sentence = words.reduce("") { $0.isEmpty ? $1 : "\($0) \($1)" }8 // The initial value is a named tuple; Int.max and Int.min make any number win the first comparison9let stats = numbers.reduce((min: Int.max, max: Int.min, sum: 0)) { result, num in // Returns a new tuple updating minimum, maximum and sum at once10 (min: min(result.min, num), max: max(result.max, num), sum: result.sum + num)11}12 // Prints Sum: 15, Product: 12013print("Sum: \(sum), Product: \(product)")// Prints Sentence: Swift is awesome14print("Sentence: \(sentence)")// Prints Stats: min=1, max=5, sum=1515print("Stats: min=\(stats.min), max=\(stats.max), sum=\(stats.sum)")Output
Sum: 15, Product: 120 Sentence: Swift is awesome Stats: min=1, max=5, sum=15
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.
(× 19)× 19,× 17"× 16.× 13:× 11=× 9\× 8$× 6{× 3