Swift map, Swift reduce and Swift filter functions

March 6, 2016

Swift map, Swift reduce and Swift filter functions

At one point or another you find yourself in a situation, where you would like to do this or that a bit differently. Or maybe asked yourself if there is another way of doing something. Or maybe you have never even asked yourself those questions. Well, in this case, you will be pleased to get to know map, reduce and filter functions.

Swift map function

Swift map function is pretty straight-forward: it iterates through your array, grabbing each of its objects where you do what you please with it. For example, it could look like this, in case you have and array of String values:

let strings = ["Swift", "is", "super cool!"]
let alteredStrings = strings.map {
    $0.stringByReplacingOccurrencesOfString("s", withString: "1")
print(alteredStrings) // ["1wift", "i1", "1uper cool!"]

Swift reduce function

Swift reduce function reduces your array to one value by taking the initial value and a function with running total. An example of usage could look like this:

let strings = ["swift", "is", "super cool!"]
let result = strings.reduce("") {
    return $0 + $1
print(result) // "swiftissuper cool!"

Swift filter function

Swift filter function filters your array, deciding whether iterated element should be included into the resulting array or not based on the true/false value returned by the function. Here's an example:

let strings = ["swift", "is", "super cool!"]
let result = strings.filter {
print(result) // ["swift", "super cool!"]

Chaining multiple functions

Cool part about all this is that you can chain these functions together to create some nice looking things, here take a look:

let strings = ["swift", "is", "super cool!"]
let result = strings.map { $0.capitalizedString }
                    .filter { $0.hasPrefix("S") }
                    .reduce("") { $0 + $1 }
print(result) // "SwiftSuper Cool!"


comments powered by Disqus