dwarvesf / til

Today I Learned. Our knowledge hub. List out what we've learned everyday, organized.
29 stars 1 forks source link

Reproduce filter function in Swift #29

Open viettrungphan opened 6 years ago

viettrungphan commented 6 years ago

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.

2.

3.

4.

5.

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.