如果我有一个数组:
let array = [
["Hamburger", "Nachos", "Lasagne"],
["Tomatoes", "Apples", "Oranges"],
["Soda", "Juice", "Water"]
]
例如"苹果"的索引是什么?有没有办法以程序化方式获得它?
答案 0 :(得分:3)
您可以使用index(where:)
并使用index(of:)
查找其子索引:
let array = [
["Hamburger", "Nachos", "Lasagne"],
["Tomatoes", "Apples", "Oranges"],
["Soda", "Juice", "Water"]
]
let query = "Apples"
if let index = array.index(where: {$0.contains(query)}),
let subIndex = array[index].index(of: query) {
print(array[index][subIndex]) // Apples
}
作为扩展名:
extension Array where Element: Collection, Element.Element: Equatable, Element.Index == Index {
func indexAndSubIndex(of element: Element.Element) -> (index: Index, subIndex: Index)? {
if let index = index(where: {$0.contains(element)}),
let subIndex = self[index].index(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.indexAndSubIndex(of: query) {
print(indexes) // "(index: 2, subIndex: 0)\n"
}
答案 1 :(得分:0)
另一种选择作为扩展。函数tupleIndex(of:)
返回(Int, Int)?
的元组。
let array = [
["Hamburger", "Nachos", "Lasagne"],
["Tomatoes", "Apples", "Oranges"],
["Soda", "Juice", "Water"]
]
extension Collection where
Element: Collection,
Element.Element: Equatable,
Element.Index == Int {
func tupleIndex(of elementToFind: Element.Element) -> (Int, Int)? {
for (firstIndex, element) in self.enumerated() {
if let secondIndex = element.index(of: elementToFind) {
return (firstIndex, secondIndex)
}
}
return nil
}
}
你可以像这样使用它:
print(array.tupleIndex(of: "Apples")) //prints Optional((1, 1))
答案 2 :(得分:0)
它不优雅但易于阅读
func getIndices(arr: [[String]], word: String) -> (Int, Int)? {
for i in 0..<arr.count {
let subArr = arr[i]
if let index = subArr.index(of: word) {
return (i, index)
}
}
return nil
}
let result = getIndices(arr: array, word: "Apples"))
答案 3 :(得分:-3)
let array = [
["Hamburger", "Nachos", "Lasagne"],
["Tomatoes", "Apples", "Oranges"],
["Soda", "Juice", "Water"]
]
for arr in array {
let answer = arr.indexOf("Apples")
if answer {
break
}
print(answer)
}