gpt4 book ai didi

swift - 在 Swift 中使用索引遍历集合的正确且惯用的方法?

转载 作者:可可西里 更新时间:2023-11-01 02:16:17 24 4
gpt4 key购买 nike

我想遍历任意 Swift 集合并获取元素及其索引。

基本上可以替代:

for (idx, el) in collection.enumerate() {
print("element at \(idx) is \(el)")
}

但这给了我真正的通用索引,而不仅仅是从 0 开始的连续整数。

当然,解决方案将成为接受任何类型集合的通用函数的一部分,否则差异不会很重要。

有没有比下面这样的简单循环更好的方法?

var idx = collection.startIndex, endIdx = collection.endIndex
while idx < endIdx {
let el = collection[idx]
print("element at \(idx) is \(el)")
idx = idx.successor()
}

看起来很容易出错的写作。我知道我可以将该代码变成一个片段,但如果可能的话,我想找到一个更简洁、更惯用的解决方案。

最佳答案

对于任何集合,indices 属性返回有效范围指数。遍历索引和相应的元素同时,您可以使用 zip():

for (idx, el) in zip(collection.indices, collection) {
print(idx, el)
}

数组切片示例:

let a = ["a", "b", "c", "d", "e", "f"]
let slice = a[2 ..< 5]

for (idx, el) in zip(slice.indices, slice) {
print("element at \(idx) is \(el)")
}

输出:

element at 2 is celement at 3 is delement at 4 is e

You can define a custom extension method for that purpose(taken from How to enumerate a slice using the original indices?):

// Swift 2:
extension CollectionType {
func indexEnumerate() -> AnySequence<(index: Index, element: Generator.Element)> {
return AnySequence(zip(indices, self))
}
}

// Swift 3:
extension Collection {
func indexEnumerate() -> AnySequence<(Indices.Iterator.Element, Iterator.Element)> {
return AnySequence(zip(indices, self))
}
}

字符 View 示例:

let chars = "a😀🇩🇪z".characters
for (idx, el) in chars.indexEnumerate() {
print("element at \(idx) is \(el)")
}

输出:

element at 0 is aelement at 1 is 😀element at 3 is 🇩🇪element at 7 is z

关于swift - 在 Swift 中使用索引遍历集合的正确且惯用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281529/

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