我试图在字典中找到条目的索引。我的字典如下:
// 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
函数采用参数闭包,该闭包确定当前值是否为您要查找的值。然后,它返回一个整数或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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句