我引用此當前夫特文檔中:迭代和變異詞典的數組夫特3
You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop. Here, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs") }
// ants have 6 legs // spiders have 8 legs // cats have 4 legs
然而,當我動態創建的字典的陣列,該代碼不起作用:
let wordArray = ["Man","Child","Woman","Dog","Rat","Goose"]
var arrayOfMutatingDictionaries = [[String:Int]]()
var count = 0
while count < 6
{
arrayOfMutatingDictionaries.append([wordArray[count]:1])
count += 1
}
根據上述程序成功創建詞典的陣列,它應該,但是當我嘗試來遍歷它像文檔顯示:
for (wordText, wordCounter) in arrayOfMutatingDictionaries
我得到一個錯誤:表達式類型[字符串:INT]]是沒有更多的上下文
曖昧我不明白,在所有。
這裏的目標是有一個可變字典的可變數組。在程序的過程中,我想添加新的鍵值對,但也可以在必要時增加值。我沒有與這種集合類型結婚,但我認爲它會起作用。
任何想法?
'arrayOfMutatingDictionaries'是*數組*,而不是一本字典,所以你會用'的字典中arrayOfMutatingDictionaries {...}'迭代。 - 不知道你在期待什麼。 –
我期待着我已經將數組聲明爲一個var,它將是可變的,但使用上面的代碼模式,這是不可能的。通過在'arrayOfMutatingDictionaries'中迭代'for dict',不可能修改字典的值,這是我想要做的。 –