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) print(array) var sArr = array.map { (value) in "\(value)" } print(sArr) var dArr = array.map { (value) in Double(value) * 2.0 } print(dArr) var bArr = array.map { (value) in value > 0 ? true : false } print(bArr) var dictionary = ["a":"11","2":"22","3":"33"] var nDic = dictionary.map { (key, value) in return key.capitalized } print(nDic)
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.