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"?
In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With