在 Swift 中查找字典条目的索引

Find index of dictionary entry in Swift

我正在尝试查找字典中条目的索引。我的词典如下:

//  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",
    ]
]

我尝试使用 indexOf 但它不起作用。我的代码如下:

// 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

indexOf 函数采用一个参数闭包来确定当前值是否是您要查找的值。然后 returns 一个整数或 NSNotFound 取决于是否找到该值。

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

这可能适合您的用例。

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

输出

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

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