Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping an index with flatMap in Swift

Tags:

swift3

flatmap

This is a follow-up to this question:

flatMap and `Ambiguous reference to member` error

There I am using the following code to convert an array of Records to an array of Persons:

let records = // load file from bundle
let persons = records.flatMap(Person.init)

Since this conversion can take some time for big files, I would like to monitor an index to feed into a progress indicator.

Is this possible with this flatMap construction? One possibility I thought of would be to send a notification in the init function, but I am thinking counting the records is also possible from within flatMap ?

like image 285
koen Avatar asked Nov 28 '16 22:11

koen


1 Answers

Yup! Use enumerated().

let records = // load file from bundle
let persons = records.enumerated().flatMap { index, record in
    print(index)
    return Person(record)
}
like image 87
Alexander Avatar answered Sep 29 '22 09:09

Alexander