Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

ios - How to get index(of:) to return multiple indices?

Here is a group array.

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"]

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

group.index(of: "A"!)

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...