Start learning free

LESSON 195 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Swift: Group by Category with a Dictionary

Practice Read the full explanation

Use a dictionary to accumulate totals per category while looping over parallel arrays, then list the categories sorted by name.

You start with:

        let items = ["Apple", "Bread", "Shirt", "Banana", "Pants"]
        let prices = [2, 3, 25, 1, 40]
        let categories = ["Food", "Food", "Clothes", "Food", "Clothes"]

Build:

Clothes: $65
Food: $6

Rules:

  • Build a dictionary totals that maps each category to the sum of the prices of its items.
  • Loop with an index. For each item, add its price to the total of categories[i]; a category you have not seen yet counts as 0.
  • Make one line per category, in the format "Category: $total", sorted alphabetically by category name (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with print(result).

Use totals[cat, default: 0] += prices[i] to accumulate without checking for missing keys.

Use totals.keys.sorted() to get the keys in alphabetical order.

        let items = ["Apple", "Bread", "Shirt", "Banana", "Pants"]
        let prices = [2, 3, 25, 1, 40]
        let categories = ["Food", "Food", "Clothes", "Food", "Clothes"]

        var totals = [String: Int]()
        for i in items.indices {
            let category = categories[i]
            totals[category, default: 0] += prices[i]
        }
        var lines = [String]()
        let keys = totals.keys.sorted()
        for category in keys {
            lines.append("\(category): $\(totals[category]!)")
        }
        let result = lines.joined(separator: "\n")
        print(result)

STEP 1 OF 10
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Swift, explained

    Problem overview

    The cart now has a category for every item. Three parallel arrays describe it: items holds the names, prices the prices and categories the category of each item, all matched by position. The program adds up the prices per category and prints one line per category, sorted by category name:

    Clothes: $65
    Food: $6

    For the starter data, the Clothes items are the shirt (25) and the pants (40), which gives 65. The food items are the apple (2), the bread (3) and the banana (1), which gives 6. Food comes first in the arrays, but the output starts with Clothes, because "Clothes" sorts before "Food".

    Approach: accumulate in a dictionary, then sort the keys

    The categories aren't known in advance, and they repeat. A dictionary from category to running total fits: for every item, find its category's entry and add the price to it. The first time a category appears it has no entry yet, so the sum has to start from 0.

    The second part is the output order. A Swift dictionary has no order you can rely on, and the order can differ from one run of the program to the next. To get alphabetical lines, take the keys, sort them, and build one line for each key in that order. Sorting the keys is cheap, because there is one key per category and not one per item.

    Step by step

    1. Create totals as an empty [String: Int] in a var. It maps each category to its sum, and a dictionary declared with let can't change.
    2. Loop over items.indices. For five items, i goes from 0 to 4 and indexes all three arrays.
    3. Read the category of the current item: categories[i], stored in a let named category.
    4. Add the price to its total with totals[category, default: 0] += prices[i]. The default: 0 covers the first item of a category, whose total doesn't exist yet.
    5. Create lines after the loop, as an empty array of strings in a var.
    6. Sort the keys. totals.keys.sorted() returns an array of the categories in alphabetical order, stored in keys.
    7. Loop over keys with category as the loop variable. It visits each category once, in sorted order.
    8. Append a line for the category: its name, a colon and a dollar sign, then its total. A plain lookup gives an optional, so ! unwraps it. The key is certain to exist, because it came from the dictionary's own keys.
    9. Join the lines into result with a newline between each two.
    10. Print result.

    The solution in Swift

            let items = ["Apple", "Bread", "Shirt", "Banana", "Pants"]
            let prices = [2, 3, 25, 1, 40]
            let categories = ["Food", "Food", "Clothes", "Food", "Clothes"]
    
            var totals = [String: Int]()
            for i in items.indices {
                let category = categories[i]
                totals[category, default: 0] += prices[i]
            }
            var lines = [String]()
            let keys = totals.keys.sorted()
            for category in keys {
                lines.append("\(category): $\(totals[category]!)")
            }
            let result = lines.joined(separator: "\n")
            print(result)
    

    The Swift details behind it:

    • [key, default:] works for writing too. The line totals[category, default: 0] += prices[i] reads the current value, or 0 if the key is missing, adds the price and stores the result under that key. It creates the entry on the first visit and updates it afterwards.
    • Without the default it doesn't compile. totals[category] += prices[i] is rejected with value of optional type 'Int?' must be unwrapped to a value of type 'Int', because the plain subscript returns an optional and += needs a real Int.
    • Dictionary order is unspecified. Array(totals.keys) can come out in a different order on different runs. That is why the keys are sorted before the second loop, instead of looping over totals directly.
    • keys is not an array. totals.keys is a special collection type of the dictionary, and sorted() turns it into an ordinary [String]. Strings sort by comparing their characters, so "Clothes" comes before "Food". Capital letters sort before small ones, so a category written in lowercase would sort after all the capitalised ones.
    • The ! unwraps an optional. totals[category]! is safe here because every key in keys exists in totals. The same ! on a key that isn't there stops the program.

    Edge cases and common mistakes

    • One category only. If every item is Food, the dictionary has a single key and the output is a single line. With the starter prices that is Food: $71.
    • Empty arrays. The loops never run, lines stays empty, and joined gives an empty string. print then outputs an empty line.
    • Looping over the dictionary itself. A for loop over totals would work, but the lines could appear in any order. The task asks for alphabetical order.
    • Forgetting the default. Without default: 0 the code doesn't compile, as shown above. Writing totals[category] = prices[i] instead would compile, but it would overwrite the earlier sum on every repeat, so Food would end up as 1, the price of the last food item.
    • Mixed-up positions. The loop uses one index for all three arrays. If the arrays were of different lengths, reading past the end of the shorter one would crash the program.
    • Case in category names. "food" and "Food" are different keys and would produce two separate lines.

    Testing

    Try these changes in the editor, using the reference solution's results:

    • With categories = ["Food", "Food", "Food", "Food", "Food"], the output is Food: $71.
    • With empty arrays ([String](), [Int]() and [String]()), the program prints a single empty line.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free