Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
993 views
in Technique[技术] by (71.8m points)

swift - How to get the index of an item in a 2D array?

If I have an array:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...