Trying to understand difference between map and flatMap output in swift

for code with flatMap

let scoresByName = ["Henk": [0, 5, 8], "John": [2, 5, 8]]

let flatMap = scoresByName.flatMap {
    $0.key
}

print(flatMap)

o/p is ["J", "o", "h", "n", "H", "e", "n", "k"]

and for code using map

let scoresByName = ["Henk": [0, 5, 8], "John": [2, 5, 8]]

let flatMap = scoresByName.map {
    $0.key
}

o/p is ["John", "Henk"]

why flatMap is splitting the keys "Henk" and "John" into characters?

>Solution :

flatMap is "map, and then flatten." "Flatten" means to turn a Sequence of Sequences in an single Array containing all the elements. [ [1,2], [3,4] ] becomes [1,2,3,4].

So the first step is the output of map, which is ["John", "Henk"]. Each of those Strings is a Sequence of Character, so flatten merges that into a single Array of Character.

Leave a Reply