在 Swift 中使用 flatMap 保留索引

Keeping an index with flatMap in Swift

这是这个问题的后续:

我正在使用以下代码将 Records 的数组转换为 Persons 的数组:

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

由于这种转换对于大文件可能需要一些时间,我想监控一个索引以输入进度指示器。

这种 flatMap 结构是否可行?我想到的一种可能性是在 init 函数中发送通知,但我认为也可以从 flatMap 中计算记录?

是啊!使用 enumerated().

let records = // load file from bundle
let persons = records.enumerated().flatMap { index, record in
    print(index)
    return Person(record)
}