You can use firstIndex(where:)
and find the subindex of it using firstIndex(of:)
:
let array = [
["Hamburger", "Nachos", "Lasagne"],
["Tomatoes", "Apples", "Oranges"],
["Soda", "Juice", "Water"]
]
let query = "Apples"
if let index = array.firstIndex(where: {$0.contains(query)}),
let subIndex = array[index].firstIndex(of: query) {
print(array[index][subIndex]) // Apples
}
As an Extension:
extension Collection where Element: Collection, Element.Element: Equatable {
func firstIndexAndSubIndex(of element: Element.Element) -> (index: Index, subIndex: Element.Index)? {
if let index = firstIndex(where: {$0.contains(element)}),
let subIndex = self[index].firstIndex(of: element) {
return (index,subIndex)
}
return nil
}
}
usage:
let array = [
["Hamburger", "Nachos", "Lasagne"],
["Tomatoes", "Apples", "Oranges"],
["Soda", "Juice", "Water"]
]
let query = "Soda"
if let indexes = array.firstIndexAndSubIndex(of: query) {
print(indexes) // "(index: 2, subIndex: 0)
"
}
This would work also to find the index of a character from an array of strings:
let array = ["Hamburger", "Nachos", "Lasagne"]
let query: Character = "h"
if let indices = array.indexAndSubIndex(of: query) {
print(indices) // "(index: 1, subIndex: Swift.String.Index(_rawBits: 196865))
"
array[indices.index][indices.subIndex] // "h"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…