简体   繁体   中英

Adding values to complex dictionary Swift

I am new to Swift and am having difficulty adding a new value to a complex dictionary. 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.

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM