Search code examples
swiftmapsreduce

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 ?

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)
        }