leisdorf
leisdorf

Reputation: 51

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 (e.g., 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)
    }

}

Upvotes: 0

Views: 171

Answers (1)

Tim Vermeulen
Tim Vermeulen

Reputation: 12562

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

Upvotes: 1

Related Questions