我是Swift的新手,并且很难在复杂字典中添加新值。下面的代码更新了字典中已存在的值(例如,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)
}
}
答案 0 :(得分:1)
localInformation[name]?["City"] = citySelected
?
基本上意味着(在此上下文中)如果localInformation[name]
为nil
则不会执行任何操作,这很可能就是这种情况。你可能想这样做:
localInformation[name] = [
"City": citySelected,
"Preference": preferenceSelected,
"Gender": "Female"
]
话虽如此,我建议您尽可能使用struct
而不是字典。它会更容易处理(因为你不能拼错一把钥匙而你不必处理很多选项),它会让你的代码更加清晰。