gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:36:55 25 4
gpt4 key购买 nike

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

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

关于swift - 在 Swift 中查找字典条目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35517695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com