map
The :map method converts each element of an array [T] into a value of type U using a closure function. The definition is as follows:
func map(transform: (T) -> U) -> [U]
filter
The filter is a filter closure that is used to filter the closure by the Bool returned by the closure function. True adds to the result array. The definition is as follows:
func filter(includeElement: (T) -> Bool) -> [T]
reduce
Given an initial value of type U, pass each element of array [T] into Combine’s closure function and compute the resulting value of type U. The definition is as follows:
func reduce(initial: U, combine: (U, T) -> U) -> U
Why Map,Filter, and Reduce
- Convenient: very little code, saving time - concise: in line with Swift language style, the code quality will be better when you use Map, Filter, reduct. But they also need to be used in the right context and don't expect to solve any problems with them. There is no universal truth. - Efficiency: Higher order functions are faster than traditional implementations when the data is large because they can be executed in parallel (e.g. running on multiple cores) and can be used all the time for faster execution unless higher custom versions of Map, Reduce, and Filter are really needed.Copy the code
Map
In OC, operating on array elements is inconvenient, traversing, manipulating, and assigning to new arrays is tedious. In Swift, the manipulation of arrays is much simpler.
Func map(transform: (T) -> U) -> [U] Func map(transform: (T) -> U) -> [U]
In Functional Programming in Swift, the map function is implemented as follows:
func map<T, U>(xs: [T], f: T -> U) -> [U]
{
var result: [U] = []
for x in xs
{
result.append(f(x))
}
return result
}
Copy the code
- Add 10 to each number to get a new array:
// Map functions can be used as parameters directly. Let numberArray = [1,2,3,4,5] Int) -> Int{ return a + 10 } var result = numberArray.map(fmap) print(result)Copy the code
Var result = numberarray. map({($0) + 10}) print(result)Copy the code
- Maps can be used not only for simple numerical operations, but also for complex operations such as concatenating strings after numbers and returning new arrays
Write in the usual way:
For number in numberArray {stringSarray.appEnd ("\(number) only ")} print(stringsArray)Copy the code
Using the map:
ResultArray = numberArray.map({"\($0) only "}) print(resultArray)Copy the code
So succinct, try using OC…
FlatMap
FlatMap is even more powerful, passing in N processing methods and combining the resulting data into the same array
ResultArray = numberArray.flatMap({["\($0) x ","\($0) only "]}) print(resultArray) // [" 1 ", "1", "2", "2", "three", "three", "four", "four", "five", "five"]Copy the code
Filter
Filter is a filter closure used to determine whether to filter, based on the Bool returned by the closure function. True adds to the result array. Filter (includeElement: (T) -> Bool) -> [T]
- Find the number in the array greater than 2
The usual way to implement:
var filteredArray : [Int] = []
for number in numberArray {
if number > 2 {
filteredArray.append(number)
}
}
print(filteredArray)
Copy the code
Use filter to implement:
filteredArray = numberArray.filter({$0 > 2})
print(filteredArray)
Copy the code
reduce
Given an initial value of type U, each element of array [T] is passed into Combine’s closure function and computed to obtain a value of type U.
Func reduce(Initial: U, combine: (U, T) -> U) -> U
A similar implementation of reduce is:
func reduce<A, R>(arr: [A], _ initialValue: R, combine: (R, A) -> R) -> R
{
var result = initialValue
for i in arr
{
result = combine(result, i)
}
return result
}
let input = [1, 2, 3, 4]
var sum = reduce(input, 0){ x, y in x + y }
Copy the code
Reduce functions can also be used to implement map functions and filter functions:
func mapUsingReduce<T, U>(xs: [T], f: T -> U) -> [U]
{
return reduce(xs, []){ result, x in result + [f(x)] }
}
var result = mapUsingReduce(input){ x in x * 3 }
result1
func filterUsingReduce<T>(xs: [T], check: T -> Bool) -> [T]
{
return reduce1(xs, [])
{
result , x in return check(x) ? result + [x] : result
}
}
result = filterUsingReduce(exampleFiles)
{
file in file.hasSuffix("swift")
}
Copy the code
- Compute the sum and product of all the numbers in the array
The usual way to implement:
var sum = 0 for number in numberArray { sum += number } print(sum) var product = 1 for number in numberArray { product = product * number } print(product)Copy the code
Using reduce:
sum = numberArray.reduce(0, combine: {$0 + $1})
print(sum)
Copy the code
It can also be written as:
sum = numberArray.reduce(0, combine: +)
Copy the code