gpt4 book ai didi

swift3 - 在 Swift 中使用 flatMap 保留索引

转载 作者:行者123 更新时间:2023-12-02 08:08:46 25 4
gpt4 key购买 nike

这是这个问题的后续:

flatMap and `Ambiguous reference to member` error

我使用以下代码将 Record 数组转换为 Person 数组:

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 { offset, record in
print(offset)
return Person(record)
}

请注意,您得到的是一个偏移量(始终从0开始计数)。正如文档所阐明的:

When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only in instances of zero-based, integer-indexed collections, such as Array and ContiguousArray. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the zip(_:_:) function.

如果您想要可以可靠地使用索引的值,请使用 zip,正如他们建议的那样:

let a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
let slice = a.dropFirst(3) // Indices start at 3

for (index, element) in zip(slice.indices, slice) {
print(slice[index], element) // The index is always valid for subscripting back into the collection
}

关于swift3 - 在 Swift 中使用 flatMap 保留索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40854733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com