您可以使用firstIndex(where:) 并使用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
}
作为扩展:
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
}
}
用法:
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)\n"
}
这也适用于从字符串数组中查找字符的索引:
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))\n"
array[indices.index][indices.subIndex] // "h"
}