gpt4 book ai didi

swift 字典 : Can't completely remove entry

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:58 24 4
gpt4 key购买 nike

我有一个 Swift 字典,我正试图完全删除一个条目。我的代码如下:

import UIKit

var questions: [[String:Any]] = [
[
"question": "What is the capital of Alabama?",
"answer": "Montgomery"
],
[
"question": "What is the capital of Alaska?",
"answer": "Juneau"
]
]

var ask1 = questions[0]
var ask2 = ask1["question"]

print(ask2!) // What is the capital of Alabama?

questions[0].removeAll()

ask1 = questions[0] // [:]
ask2 = ask1["question"] // nil - Should be "What is the capital of Alaska?"

我使用 questions[0].removeAll() 删除了条目,但它留下了一个空条目。我怎样才能完全删除条目以便没有痕迹?

最佳答案

此行为没有任何问题,您是在告诉编译器删除 Dictionary 中的所有元素。它工作正常:

questions[0].removeAll()

但是您要声明一个 Array<Dictionary<String, Any>>或简写语法 [[String: Any]]如果你想删除 Dictionary,你也需要从你的数组中删除条目,请看下面的代码:

var questions: [[String: Any]] = [
[
"question": "What is the capital of Alabama?",
"answer": "Montgomery"
],
[
"question": "What is the capital of Alaska?",
"answer": "Juneau"
]
]

var ask1 = questions[0]
var ask2 = ask1["question"]

print(ask2!) // What is the capital of Alabama?

questions[0].removeAll()

questions.removeAtIndex(0) // removes the entry from the array in position 0

ask1 = questions[0] // ["answer": "Juneau", "question": "What is the capital of Alaska?"]
ask2 = ask1["question"] // "What is the capital of Alaska?"

希望对你有帮助

关于 swift 字典 : Can't completely remove entry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35494051/

24 4 0