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
- Create
totalsas an empty[String: Int]in avar. It maps each category to its sum, and a dictionary declared withletcan't change. - Loop over
items.indices. For five items,igoes from 0 to 4 and indexes all three arrays. - Read the category of the current item:
categories[i], stored in aletnamedcategory. - Add the price to its total with
totals[category, default: 0] += prices[i]. Thedefault: 0covers the first item of a category, whose total doesn't exist yet. - Create
linesafter the loop, as an empty array of strings in avar. - Sort the keys.
totals.keys.sorted()returns an array of the categories in alphabetical order, stored inkeys. - Loop over
keyswithcategoryas the loop variable. It visits each category once, in sorted order. - 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. - Join the lines into
resultwith a newline between each two. - 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 linetotals[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 withvalue of optional type 'Int?' must be unwrapped to a value of type 'Int', because the plain subscript returns an optional and+=needs a realInt. - 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 overtotalsdirectly. keysis not an array.totals.keysis a special collection type of the dictionary, andsorted()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 inkeysexists intotals. 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,
linesstays empty, andjoinedgives an empty string.printthen outputs an empty line. - Looping over the dictionary itself. A
forloop overtotalswould work, but the lines could appear in any order. The task asks for alphabetical order. - Forgetting the default. Without
default: 0the code doesn't compile, as shown above. Writingtotals[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 isFood: $71. - With empty arrays (
[String](),[Int]()and[String]()), the program prints a single empty line.
