How to use: Map, Filter and Reduce in Swift
The Map is an extension method on Sequence and Collection. The map function returns an array containing the results of applying a mapping or transform function to each item.let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercaseString }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
2, Filter
It Returns an array containing, in order, the elements of the sequence that satisfy the given predicate. It’s a very useful operation which allows us to filter the existing collection and return an Array containing only those elements that match an include condition.
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 } // return only names which have shorter than five characters
print(shortNames)
// Prints "["Kim", "Karl"]"
3, Reduce
The reduce function is super useful for when you need to reduce a set of values down to a single value. In short, Use reduce to combine all items in a collection to create a single new value.
Thanks for reading, Happy Coding 👨💻
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
Thanks for reading, Happy Coding 👨💻