Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // map - transform each element let squares = numbers.map { $0 * $0 } // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] // filter - keep elements matching predicate let evens = numbers.filter { $0 % 2 == 0 } // [2, 4, 6, 8, 10] // reduce - fold into single value let total = numbers.reduce(0, +) // 55 // compactMap - map + unwrap optionals let strings = ["1", "two", "3", "four", "5"] let ints = strings.compactMap { Int($0) } // [1, 3, 5] // flatMap - flatten nested collections let nested = [[1, 2], [3, 4], [5, 6]] let flat = nested.flatMap { $0 } // [1, 2, 3, 4, 5, 6] // Chain operations let result = numbers .filter { $0 % 2 == 0 } .map { $0 * $0 } .reduce(0, +) print(result) // 220 // Function as parameter func applyTwice(_ f: (Int) -> Int, to value: Int) -> Int { f(f(value)) } let double = { (x: Int) -> Int in x * 2 } print(applyTwice(double, to: 3)) // 12
Result
Open