Drilling Higher Order Function | Map | Swift

For those, who knows what and how to use closures (more? read the article here) and what generic is this will be straight forward. So here we have, Higher order functions are the functions that take as the argument or returns a function. Just feed an array and it does stuff with them in order to return a new array but not only the same type.

Use the map to loop over a collection and apply some operation to each element in the collection and beauty is it will return a new array(not restricted to the input type) and in the end, it will return the final array.

var array = [Int].init(repeating: 1, count:5)

var sArr = array.map { (value) in

var dArr = array.map { (value) in
    Double(value) * 2.0

var bArr = array.map { (value) in
    value > 0 ? true : false

var dictionary = ["a":"11","2":"22","3":"33"]
var nDic = dictionary.map { (key, value) in
    return key.capitalized

How does it work? it has a single argument which is a closure that it calls as it loop over and over the collection. The map function returns these results in an array.

Interesting right? And even in the last blog, i have also compared the performance of using .map and basic for-in loop, results were highly surprising.

Thank you for reading! Share your comment & thoughts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.