小编典典

如何获取index(of :)以返回多个索引?

swift

这是一个组数组。

var group = ["H","H","E","D",
             "G","D","G","E",
             "D","B","A","B",
             "A","A","G","C",
             "C","H","D","G",
             "H","B","E","F",
             "F","C","E","A",
             "B","C","F","F"]

我想做这样的事情来找到“ A”的索引。

group.index(of: "A"!)

但这将仅返回第一个索引,而后三个“ A”则不返回其他索引。

print(group.index(of: "A")!) //10

如何使程序返回“ A”的所有四个索引?


阅读 486

收藏
2020-07-07

共1个答案

小编典典

您可以使用的组合enumeratedcompactMap

let indexArray = group.enumerated().compactMap {
   $0.element == "A" ? $0.offset : nil
}    
print(indexArray) // [10, 12, 13, 27]
2020-07-07