如何获取二维数组中项目的索引? [英] How to get the index of an item in a 2D array?

查看:62
本文介绍了如何获取二维数组中项目的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个数组:

let array = [
        ["Hamburger", "Nachos", "Lasagne"],
        ["Tomatoes", "Apples", "Oranges"],
        ["Soda", "Juice", "Water"]
    ]    

例如Apples"的索引是什么?有没有办法以编程方式获取它?

What is the index of for example "Apples"? And is there a way to get it programmaticly?

推荐答案

您可以使用 firstIndex(where:) 并使用 firstIndex(of:) 找到它的子索引>:

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

}

作为扩展:

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


这也适用于从字符串数组中查找字符的索引:


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))\n"
    array[indices.index][indices.subIndex]  // "h"
}

这篇关于如何获取二维数组中项目的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆