Updating Dictionaries
Part of the Logic & Flow section of Coddy's Swift journey — lesson 14 of 56.
You write to a dictionary the same way you read from one: with the subscript.
var prices: [String: Int] = ["apple": 1]
prices["bread"] = 3 // adds the key
prices["apple"] = 2 // updates an existing key
prices["apple"] = nil // removes the keyTwo named methods do the same thing more explicitly:
prices.updateValue(5, forKey: "milk") // returns the old value, or nil
prices.removeValue(forKey: "bread") // returns the removed value, or nilThe named methods return the previous value, which is useful when you need to know whether the key already existed.
The default-subscript pattern from the previous lesson chains perfectly with mutation, this is how you build a counter without writing an if:
var counts: [String: Int] = [:]
for letter in ["a", "b", "a"] {
counts[letter, default: 0] += 1
}
// counts == ["a": 2, "b": 1]Challenge
MediumRead a single line of input: a comma-separated list of operations on a starting dictionary. Each operation is one of:
set:<key>:<value>add or update (value is an integer)add:<key>:<value>add the value to the existing one (use the default-subscript pattern)del:<key>remove the key
After applying every operation in order to an initially-empty [String: Int], print the keys in alphabetical order, one per line, in the format <key>=<value>.
For input set:a:5,add:a:3,set:b:1,del:b,add:c:2, the output is:
a=8
c=2Cheat sheet
Modify a dictionary using subscript or named methods:
prices["bread"] = 3 // add
prices["apple"] = 2 // update
prices["apple"] = nil // remove
prices.updateValue(5, forKey: "milk") // returns old value or nil
prices.removeValue(forKey: "bread") // returns removed value or nilUse the default-subscript pattern to mutate without if:
var counts: [String: Int] = [:]
for letter in ["a", "b", "a"] {
counts[letter, default: 0] += 1
}
// counts == ["a": 2, "b": 1]Try it yourself
let ops = readLine()!.components(separatedBy: ",")
var dict: [String: Int] = [:]
// TODO: parse each op and apply set/add/del; print sorted keys with values
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check3Dictionaries
Declaring DictionariesOptional LookupUpdating DictionariesIterating DictionariesGrouping ValuesRecap - Inventory