如何让 index(of:) 返回多个索引? [英] How to get index(of:) to return multiple indices?

查看:42
本文介绍了如何让 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"的索引.

I want to do something like this to find indices of "A".

group.index(of: "A"!)

但这只会返回第一个索引,而不返回接下来三个A"的其他索引.

But this will return only first index, but not other indices for next three "A"s.

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

我该怎么做才能让程序返回A"的所有四个索引?

What do I do to get the program to return all four indices for "A"?

推荐答案

您可能会使用 enumeratedcompactMap 的组合:

You might use a combination of enumerated and compactMap:

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

这篇关于如何让 index(of:) 返回多个索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆