Swift 2.2: What is the difference between .map and .flatMap?

When you dive into .map and .flatMap ocean, you may be confused what is the difference. Consider such example:

let arr = [1,2,3,4,5,6]
print(arr.map{ return String($0 * 2)+"x" })
print(arr.flatMap{ return String($0 * 2)+"x" })

Both print’s, will give you same result:

["2x", "4x", "6x", "8x", "10x", "12x"]

So why bother? The main details between them, is that flatMap will skip nil values and unwraps them, so the example:

let mapArr = arr.map{ (string:Int) -> String? in
    if string < 2 {
        return nil
    }
    return String(string * 2)+"x"
}
print(mapArr)
let mapArr2 = arr.flatMap{ (string:Int) -> String? in
    if string < 2 {
        return nil
    }
    return String(string * 2)+"x"
}
print(mapArr2)

will give following results:

[nil, Optional("4x"), Optional("6x"), Optional("8x"), Optional("10x"), Optional("12x")]
["4x", "6x", "8x", "10x", "12x"]

As you can see now .map output are all optionals with nil as first value is skipped. In .flatMap each value is unwrapped to String and there is no nil values at all.

Leave a Reply