这是一个组数组。
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”的所有四个索引?
您可以使用的组合enumerated和compactMap:
enumerated
compactMap
let indexArray = group.enumerated().compactMap { $0.element == "A" ? $0.offset : nil } print(indexArray) // [10, 12, 13, 27]