[英]Adding values to complex dictionary Swift
I am new to Swift and am having difficulty adding a new value to a complex dictionary. 我是Swift的新手,很难为复杂的字典添加新值。 The below code updates values that already exist in the dictionary (eg, Jerry and Beth), but if I try to add a new value, the dictionary shows only two values rather than three. 下面的代码更新了字典中已经存在的值(例如Jerry和Beth),但是如果我尝试添加新值,则字典仅显示两个值,而不是三个。
var locals: [String: Dictionary<String, String>] = ["Jerry":["City":Destination.Seattle.rawValue,"Preference": TravellingPreference.Adventurer.rawValue, "Gender": Gender.Male.rawValue],"Beth":["City":Destination.Seattle.rawValue,"Preference":TravellingPreference.Foodie.rawValue, "Gender": Gender.Female.rawValue]]
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
let citySelected = localInput[0][pickerView.selectedRowInComponent(0)]
let preferenceSelected = localInput[1][pickerView.selectedRowInComponent(1)]
var localInformation = LocalsInformation().locals
if let name = nameTextField.text{
localInformation[name]?["City"] = citySelected
localInformation[name]?["Preference"] = preferenceSelected
localInformation[name]?["Gender"] = "Female"
print(localInformation)
}
}
localInformation[name]?["City"] = citySelected
The ?
?
basically means (in this context) that nothing is done if localInformation[name]
is nil
, which is most likely the case. 基本上意味着(在这种情况下)如果localInformation[name]
为nil
,则什么也不做,这很可能是这种情况。 You probably want to do this: 您可能想这样做:
localInformation[name] = [
"City": citySelected,
"Preference": preferenceSelected,
"Gender": "Female"
]
Having said that, I would greatly advise you to use struct
s rather than dictionaries wherever you can. 话虽如此,我强烈建议您在任何可能的地方使用struct
而不是字典。 It will be easier to deal with (because you can't misspell a key and you won't have to deal with as many optionals), and it will make your code clearer overall. 这将更易于处理(因为您不会误拼密钥,并且您不必处理尽可能多的可选键),并且它将使您的代码更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.