2017-03-02 65 views
-1

我引用此當前夫特文檔中:迭代和變異詞典的數組夫特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]]是沒有更多的上下文

曖昧我不明白,在所有。

這裏的目標是有一個可變字典的可變數組。在程序的過程中,我想添加新的鍵值對,但也可以在必要時增加值。我沒有與這種集合類型結婚,但我認爲它會起作用。

任何想法?

+1

'arrayOfMutatingDictionaries'是*數組*,而不是一本字典,所以你會用'的字典中arrayOfMutatingDictionaries {...}'迭代。 - 不知道你在期待什麼。 –

+0

我期待着我已經將數組聲明爲一個var,它將是可變的,但使用上面的代碼模式,這是不可能的。通過在'arrayOfMutatingDictionaries'中迭代'for dict',不可能修改字典的值,這是我想要做的。 –

回答

2

你正在嘗試遍歷一個數組來對待它,就像字典。 你必須通過數組進行迭代,然後通過你的鍵/值對

for dictionary in arrayOfMutatingDictionaries{ 
    for (key,value) in dictionary{ 
     //Do your stuff 
    } 
} 

添加鍵/值對是非常簡單的。

for i in 0..< arrayOfMutatingDictionaries.count{ 
    arrayOfMutatingDictionaries[i][yourkey] = yourvalue 
} 

也可以增加現有值這樣

for i in 0..<arrayOfMutatingDictionaries.count{ 
    for (key,value) in arrayOfMutatingDictionaries[i]{ 
     arrayOfMutatingDictionaries[i][key] = value+1 
    } 
} 
1
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 dictionary in arrayOfMutatingDictionaries { // You missed this out! 
    for (word, num) in dictionary { 
    print(word, num) 
    } 
} 
+0

這有幫助,除了當我測試鵝的字典 - '如果word ==「鵝」{num + = 1}'然後我得到錯誤**變異運算符的左側是不可變的,num是一個讓常量** –

0

試試這個。你會得到你的預期結果。

let wordArray = ["Man","Child","Woman","Dog","Rat","Goose"] 
var arrayOfMutatingDictionaries = [String]() 
//Here you are doing mistake in above line. You are creating an array of dictionary ([[String:Int]]) in your code. And you are iterating an array of string (wordArray) 

var count = 0 

while count < 6 
{ 
    arrayOfMutatingDictionaries.append(wordArray[count]) 
    count += 1 
} 

for (wordText) in arrayOfMutatingDictionaries 
{ 
    print(wordText) 
}