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

时间:2016-02-20 00:47:28

标签: swift swift-dictionary

我试图找到字典中条目的索引。我的字典如下:

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

2 个答案:

答案 0 :(得分:4)

indexOf函数采用参数闭包来确定当前值是否是您正在寻找的值。然后根据是否找到值返回一个整数或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

答案 1 :(得分:0)

这可能适合您的使用案例。

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

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