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

这是一个组数组。

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”的所有四个索引?

回答:

您可以使用的组合enumeratedcompactMap

let indexArray = group.enumerated().compactMap {

$0.element == "A" ? $0.offset : nil

}

print(indexArray) // [10, 12, 13, 27]

以上是 如何获取index(of :)以返回多个索引? 的全部内容, 来源链接: utcz.com/qa/402187.html

回到顶部