Start learning free

LESSON 132 OF 292 · DICTIONARIES - CHALLENGES

Restock in Swift: Updating a Dictionary Value

Practice Read the full explanation

A shop keeps its stock in inventory, a Dictionary from item names to how many of each item it has. A delivery brings amount more of item. Add amount to the count of item and return the updated dictionary.

Only the count of item changes: every other entry stays as it is. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas", amount = 3
Output: {"apples": 5, "bananas": 5, "cherries": 10}
Explanation: "bananas" had a count of 2, and 2 + 3 = 5. The apples and the cherries keep their counts.

Example 2:

Input: inventory = {"milk": 0}, item = "milk", amount = 12
Output: {"milk": 12}
Explanation: A count of 0 means the milk was sold out. The delivery brings it to 0 + 12 = 12.

Example 3:

Input: inventory = {"pens": 7, "paper": 3}, item = "pens", amount = 1
Output: {"pens": 8, "paper": 3}
Explanation: One more pen: 7 + 1 = 8.

 

Constraints:

  • item is always a key of inventory.
  • amount is at least 1.
  • Every count is 0 or more.
  • Item names are single lowercase words, and they are all different.
STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · DICTIONARIES - CHALLENGES

    Restock in Swift, explained

    Problem overview

    The function restock receives inventory, a dictionary of type [String: Int] from item names to counts, an item that is always one of its keys, and an amount of at least 1. It adds amount to the count of item and returns the updated dictionary. All other entries stay the same, and the order of the entries doesn't matter.

    With inventory = ["apples": 5, "bananas": 2, "cherries": 10], item = "bananas" and amount = 3, the count for "bananas" goes from 2 to 5. The apples stay at 5 and the cherries at 10. With ["milk": 0], "milk" and 12, the result is ["milk": 12].

    Approach

    The new count is the old count plus amount, stored under the same key. Swift dictionaries are value types, so you first copy the parameter into a variable, change one entry in the copy, and return it. The caller's dictionary is untouched: after restock(inv, "bananas", 3), inv["bananas"]! is still 2.

    Think of the dictionary as a table of item names and counts. Restocking changes one cell of that table: find the row for item, read its count, and write back the count plus amount. No other row is touched, which is why the lesson says every other entry stays as it is.

    The copy is what keeps the function honest. A function that returns a changed dictionary while leaving the input as it was is easier to reason about, and Swift's value semantics make that the default: the copy you modify is separate from the caller's original.

    Step by step

    1. Copy the parameter into a var named result. Parameters are constants, so assigning into inventory directly is a compile error. Assigning a dictionary copies it.
    2. Set result[item] to the old count plus amount. Reading result[item] gives an Int?, because Swift can't know the key exists. The ! unwraps it to an Int, which is safe here because item is always a key.
    3. Return result.

    The solution in Swift

    class Solution {
        func restock(_ inventory: [String: Int], _ item: String, _ amount: Int) -> [String: Int] {
            var result = inventory
            result[item] = result[item]! + amount
            return result
        }
    }
    

    Swift details to notice:

    • Assigning through a subscript. result[item] = value sets the value for a key. If the key exists, its value is replaced. If it doesn't, the key is added. The assigned value is wrapped in an optional automatically, and assigning nil would remove the key.
    • Two optionals, two different jobs. The ! on the right unwraps the old count. The assignment on the left accepts an Int?, so no unwrapping is needed there.
    • Unordered output. A Swift dictionary has no guaranteed order, which is why the statement says the order doesn't matter. Printing the same dictionary twice in different runs can list the keys differently.

    Edge cases and common mistakes

    • A count of 0. ["milk": 0] is an entry with the value 0, not a missing key, so result["milk"]! works and the result is 12.
    • Replacing instead of adding. result[item] = amount would erase the old count.
    • Forgetting the copy. Writing into the parameter doesn't compile.
    • Forgetting !. result[item] + amount fails to compile, because an Int? can't be added to an Int.

    Testing

    • ["apples": 5, "bananas": 2, "cherries": 10], "bananas", 3 gives apples 5, bananas 5, cherries 10.
    • ["milk": 0], "milk", 12 gives ["milk": 12].
    • ["pens": 7, "paper": 3], "pens", 1 gives paper 3 and pens 8.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free