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

Issues with swift map chaining

One qq about maps and chaining.
Below code works perfectly fine

    var raceResults = [["one","two","four"],["two","one","five","six"],["two","one","four","ten"],["one","two","four"]]

let numberedRaceResults = raceResults
    .enumerated()
    .flatMap { outterOffset, raceResult in
        raceResult
            .enumerated()
            .map { innerOffset, element in "\(outterOffset).\(innerOffset). \(element)" }
    }

for numberedResult in numberedRaceResults {
    print(numberedResult)
}

But when I add two print statements in it , it stops working.
Can someone-one please help me to understand

1.what’s the deal with those print statements
2. If I replace flatmap with map, code below does not work. My understanding about flatmap is it just eliminates the nil values . Is there something on top of it that flatmap does comapred to map which is why I am not getting expected results when I replace flatmap with 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

var raceResults = [["one","two","four"],["two","one","five","six"],["two","one","four","ten"],["one","two","four"]]

let numberedRaceResults = raceResults
    .enumerated()
    .flatMap { outterOffset, raceResult in
        print(outterOffset)
        print(raceResult)
        raceResult
            .enumerated()
            .map { innerOffset, element in "\(outterOffset).\(innerOffset). \(element)" }
    }

for numberedResult in numberedRaceResults {
    print(numberedResult)
} 

>Solution :

When you write many lines inside the {} of flatMap function you need to tell it what should be the result and since print returns () / void ,hence you get nothing , so you need to add a return under the two prints

    let numberedRaceResults = raceResults
        .enumerated()
        .flatMap { outterOffset, raceResult in
            print(outterOffset)
            print(raceResult)
            return raceResult // here  
                .enumerated()
                .map { innerOffset, element in "\(outterOffset).\(innerOffset). \(element)" }
        }

    for numberedResult in numberedRaceResults {
        print(numberedResult)
    }
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