2015-11-04 100 views
0

我一直使用的字典在我的代碼,他們都工作,我想希望本字典的方式:解釋工作不正常

switchState["index"+("\(cellNumber)")] = cellNumber 

這裏面有個for incellNumber是變量之一。該cellNumber代表UISwitch用戶開啓。

這本詞典繼續改寫自己,我想不通爲什麼。該"index"+("\(cellNumber)")應該給字典一個新的密鑰存儲cellNumber是否正確?

我試圖將此存儲到NSUserDefaults作爲NSDictionary和swift使我有一個String的密鑰或它不會存儲它。所以當我存儲Dictionary時只存在一個值。你能看到上述Code有問題,或者有另一種方法來做到這一點。

感謝您的幫助。

回答

1
// Dictionaty<key,Value> 
// subscript(key: Key) -> Value? 
// key can be Int, Double, String .... any Type: Hashable 
// value can be Any (any number, string, struct, enumeration .... class) 

var dict: Dictionary<Int,Int> = [1:1] 

// key value 
dict[10] = 100 
dict[1] = 64364 
dict[76575] = 1 

dict.forEach { (key, value) ->() in 
    print("storage for key: \(key) has value: \(value)") 
    /* 
    storage for key: 76575 has value: 1 
    storage for key: 1 has value: 64364 
    storage for key: 10 has value: 100 
    */ 
} 

var dict2 = [1:"alfa",2:"beta",3:"game"] // [2: "beta", 3: "game", 1: "alfa"] 

dict2.forEach { (key, value) ->() in 
    print("storage for key: \(key) has value: \(value)") 
    /* 
    storage for key: 2 has value: beta 
    storage for key: 3 has value: game 
    storage for key: 1 has value: alfa 
    */ 
} 
let key = 2 
dict2.updateValue("HELLO", forKey: key) // returns string "beta" (old stored value) 
print("now the value for key \(key) has value:", dict2[key]) 
/* 
now the value for key 2 has value: Optional("HELLO") 

why Optional? 
*/ 
print("the value for key \(-3) has value:", dict2[-3]) 
/* 
the value for key -3 has value: nil 

How to remove value? 
*/ 
dict2.removeValueForKey(1) // returns string "alfa" (old value) 
dict2[1]     // return nil, as expected 

必須爲關鍵cellNumber保存開關爲布爾值的字符串

var dict: [String:Bool] = [:] 
for i in 10...15 { 
    let j = i % 3 
    dict.updateValue(j == 0, forKey: "switch\(i)") 
} 
print(dict) 
/* 
["switch12": true, "switch13": false, "switch11": false, "switch14": false, "switch10": false, "switch15": true] 
*/ 
+0

感謝您的解釋,我知道一個dicitionary可以是任何東西。但我正在專門討論保存到'NSUserDefaults'。在Swift中,當你想將'NSDictionary'保存爲'NSUserDefaults'時,它只能處理'[String:AnyObject?]'。此外,我在表格中有多個開關,它們的索引都不同。所以如果我可以存儲'索引即。 cellNumber'和字典中'switch'的狀態,然後將它存儲到'NSUserDefaults'中,這將解決我的問題。我會嘗試你最後的建議並讓你知道。謝謝。 – Rico

+0

你麻煩的是,保存(鍵,值)(密鑰,密鑰)字典[「\(密鑰)」] =鍵。但你需要將其保存像字典[「\(鑰匙」] =值WhatEverYouNeed爲有效NSUserDefaults的對。 – user3441734

+0

所以我保存它像這樣'switchState [(「\(cellNumber)」)] = TRUE;但它仍然覆蓋本身我每次調用'.count'詞典中,以確保其正常複製,但每次都只是大小1有什麼想法 – Rico

0

首先,代碼可以簡化爲:

swiftchState["index\(cellNumber)"] = cellNumber 

您應該檢查每一個循環中,cellNumber值的變化。

+0

@Si_Te_Feng感謝簡化。我想知道你是否知道爲什麼字典每次都會覆蓋自己?我知道它不能正確複製,因爲我試着'switchState.count',它總是返回1.任何想法。 – Rico

+0

您是否確定每個循環的cellNumber都不相同? –

+0

@Si_Te_Feng我做了,它確實如此。感謝您的幫助,我找到了問題。 – Rico