Find index of dictionary entry in Swift

5.7k views Asked by At

I am trying to find the index of an entry in a dictionary. My dictionary is as follows:

//  Dictionary
var questions: [[String:Any]] = [
    [
        "quesID": 1000,
        "question": "What is the capital of Alabama?",
        "answer": "Montgomery",
    ],
    [
        "quesID": 1001,
        "question": "What is the capital of Alaska?",
        "answer": "Juneau",
    ]
]

I tried using indexOf but it does not work. My code is as follows:

// Find index of dictionary entry with quesID of 1000
let indexOfA = questions.indexOf(1000) // Should return 0

// Find index of dictionary entry with quesID of 1001
let indexOfB = questions.indexOf(1001) // Should return 1
2

There are 2 answers

0
max_ On BEST ANSWER

The indexOf function takes a parameter closure which determines whether or not the current value is the one that you're looking for. It then returns an integer or NSNotFound depending on whether the value was found or not.

var questions: [[String:Any]] = [
    [
        "quesID": 1000,
        "question": "What is the capital of Alabama?",
        "answer": "Montgomery",
    ],
    [
        "quesID": 1001,
        "question": "What is the capital of Alaska?",
        "answer": "Juneau",
    ]
]

func indexOfQuestion(id: Int) -> Int {
    return questions.indexOf { (question) -> Bool in
        return question["quesID"] as? Int == id
    } ?? NSNotFound
}

let indexOfA = indexOfQuestion(1000) // 0
let indexOfB = indexOfQuestion(1001) // 1
let nonexistentIndex = indexOfQuestion(1002) // 9223372036854775807
0
Ashok R On

This may suite your use Case.

for (index, element) in questions.enumerated() {
    print("index = \(index)")
    print("element[\"quesID\"] =  \(element["quesID"]!)")
    print("element[\"question\"] =  \(element["question"]!)")
    print("element[\"answer\"] =  \(element["answer"]!)")

    print("\n*************\n")
}

Output

index = 0
element["quesID"] =  1000
element["question"] =  What is the capital of Alabama?
element["answer"] =  Montgomery

*************

index = 1
element["quesID"] =  1001
element["question"] =  What is the capital of Alaska?
element["answer"] =  Juneau

*************