Swift 词典:无法完全删除条目

Swift Dictionary: Can't completely remove entry

我有一本 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>> 或 shorthand 语法 [[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?"

希望对你有所帮助。