2

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

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

2 回答 2

5

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
于 2016-02-20T00:56:58.960 回答
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

*************
于 2016-11-04T03:57:41.237 回答