我有一个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?"
我使用问题[0] .removeAll()来删除条目,但它留下一个空条目。如何完全删除条目以便没有跟踪?
答案 0 :(得分:3)
这种行为没有任何问题,你告诉编译器删除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?"
我希望这对你有所帮助。