Collections

Swift provides some high-order function to work with collections.

mapping

map() function transform sequence of values to new array. It is a shorthand closure-based replacement for for-in statement.

let numbers = ["1", "2", "3"]
let ints = numbers.map { Int($0) }
print(ints) // [1, 2, 3]

// with for-in you must create and fill array by self

Also you can use map() function with dictionary.

let dictionary = ["foo": 1, "bar": 2, "baz": 3]
let tupleArray = dictionary.map { ($0, $1 + 1) } 
let newDictionary = Dictionary(uniqueKeysWithValues: tupleArray)

/* with full syntax
let tupleArray = dictionary.map { (key: String, value: Int) in
    return (key, value + 1)
}
*/

compactMap() function transform sequence of values to new array. Unlike map() it is discard nil values.

let numbers = ["1", "2", "not number"]
print(numbers.compactMap { Int($0) }) // [1, 2]
print(numbers.compactMap(Int.init)) // [1, 2]
print(numbers.map { Int($0) }) // [1, 2, nil]

flatMap() function transform sequence of values to new array. Unlike map() it flattens the resulting “array of arrays” into a single array.

filtering

filter() function return the elements of the sequence that satisfy the given predicate.

let values = [5, 9, 4, 6, 13, 11, 15, 8]
let even = values.filter { $0.isMultiple(of: 2) }

let dic = ["foo": 1, "bar": 4, "baz": 3]
let filtered = dic.filter { key, value in
    return value.isMultiple(of: 2)
}

reduce

reduce() function iterates over elements of the sequence and calculate a single value.

let values = [1, 2, 3]
let sum = values.reduce(0, +)
print(sum) // 6