1

我有一个 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() 删除条目,但它留下了一个空条目。我怎样才能完全删除一个条目以便没有痕迹?

4

1 回答 1

3

这种行为没有任何问题,您告诉编译器删除 a 中的所有元素Dictionary并且它工作正常:

questions[0].removeAll()

但是您声明Array<Dictionary<String, Any>>or 是简写语法[[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?"

我希望这对你有帮助。

于 2016-02-18T22:58:26.473 回答