As we know Swift support functional programming language.
The easy to see benefits from that is how easy to use filter, map, flatmap, reduce, sort etc… on Array instead of loop though array
We are not going to explain what functional programming is in this topic, just one thing keep in mind: it accept function as parameter(s) of function.
To explain how it work, let reproduce filter function
let array = [1,2,0,3 ,7]
Apple filter:
let largeThanOnes = array.filter{$0 > 1}
// print [2,3,7]
Let build our custom one
Extension existed Swift array to add “myFilter” function
extension Array{
1. func myFilter(_ condition:(Element)->Bool) -> [Element] {
2. var temp:[Element] = []
3. for t in self {
4. if condition(t) {
temp.append(t)
}
}
5. return temp
}
}
1.
This func named “myFilter” and has one parameter: “ (Element)->Bool “.
The parameter is a closure "condition" take “Element” of array as it parameter them return true/false logic.
The myFilter function return new Array of "Element" that match parameter “condition”
2.
Temp array hold filtered Element
3.
Loop though array to check each element
4.
If element match condition then put it in temp array
5.
Return Filtered Array
How to use it
let array = [1,2,0,3 ,7]
array.myFilter({item in
return item > 0
})
However swift can omit closure to become sorter because it can access item by position and inference return type
array.myFilter({$0 > 1})
and sorter
array.myFilter{$0 > 1}
Result:
Reproduce Swift filter.
Concussion:
Apply functional programming help our code easy to write, easy to read(readable) easy to understand, reduce code to write.
As we know Swift support functional programming language. The easy to see benefits from that is how easy to use filter, map, flatmap, reduce, sort etc… on Array instead of loop though array We are not going to explain what functional programming is in this topic, just one thing keep in mind: it accept function as parameter(s) of function.
To explain how it work, let reproduce filter function
Let build our custom one Extension existed Swift array to add “myFilter” function
1.
2.
3.
4.
5.
How to use it
However swift can omit closure to become sorter because it can access item by position and inference return type
array.myFilter({$0 > 1})
and sorter
array.myFilter{$0 > 1}
Result: Reproduce Swift filter.
Concussion: Apply functional programming help our code easy to write, easy to read(readable) easy to understand, reduce code to write.