technerd
technerd

Reputation: 14504

How to write higher order functions like map, filter, reduce etc.?

I am trying to write or implement my own higher order function my way, but not able to write it. In below code I tried to write filter.

    var array : [String] = ["Sagar","Harshit","Parth","Gunja","Marmik","Sachin","Saurav"]

   //Native filter function of Swift

    array = array.filter { (name) -> Bool in
        return name.prefix(1) == "S"
    }

I implement below code, according to method signature of filter, but as I know , we can not write closure with return type(If possible then I don't know).

func filterArray(_ array : [String], completionHandler : (_ name : String) -> ()) -> (){

    for (_, value) in array.enumerated(){
        completionHandler(value)
    }
}


    self.filterArray(array) { (name) -> () in
        if name.prefix(1) != "S"{
            if let index = array.index(of: name){
                array.remove(at: index)
            }
        }
    }

My implementation working fine and filtering array. But I want to abstract logic of remove object from array.

Can we write our own higher order functions or not ? If yes then please help to implement above one. Thanks in advance.

Upvotes: 0

Views: 1606

Answers (1)

danieltmbr
danieltmbr

Reputation: 1042

And you can define a return type to a closure. You can find a working example below, but for this purpose I suggest using the Swift built in filter function which can provide the same solution and much faster.

var array : [String] = ["Sagar","Harshit","Parth","Gunja","Marmik","Sachin","Saurav"]

func filterArray(_ array : inout [String], condition: (_ name : String) -> Bool) -> (){

    var filteredArray: [String] = []
    for value in array {
        if condition(value) {
            filteredArray.append(value)
        }
    }
    array = filteredArray
}

filterArray(&array) { (name) -> Bool in
    return !name.hasPrefix("S")
}

print(array)

You can define your own higher order functions on collections. There is a great session about collections where Soroush shows an example of writing your own higher order function extending a collection.

https://academy.realm.io/posts/try-swift-soroush-khanlou-sequence-collection/

// Swit built in filter
let numberOfAdmins = users.filter({ $0.isAdmin }).count // => fine 
// Custom "filter"
let numberOfAdmins = users.count({ $0.isAdmin }) // => great

extension Sequence {

    func count(_ shouldCount: (Iterator.Element) -> Bool) -> Int {

        var count = 0
        for element in self {
           if shouldCount(element) {
               count += 1
           }
        }
        return count
    } 
}

Upvotes: 2

Related Questions