Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading