Problem overview
The cart now holds several items, stored in three parallel arrays: items has the names, prices has the price of one unit, and quantities says how many units were bought. Position i in each array describes the same item. For the starter data, "Shirt", 25 and 2 all sit at position 0.
The program prints one line per item in the form Name xQ: $subtotal, where the subtotal is the price times the quantity. A final line shows the total of all subtotals:
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
Earlier versions handled one subtotal at a time. This one has to repeat the same work for every item, which is what a loop is for.
Approach: one pass, two jobs
Each item needs the same two things: a line of text and a contribution to the running total. A single for loop over the positions does both. Inside the loop, prices[i] * quantities[i] gives the item's subtotal. The loop adds that subtotal to total and appends the item's line to an array of strings.
The final Total line can't be written until every item has been added, so it comes after the loop. Collecting the lines in an array and joining them at the end avoids managing newlines by hand: joined(separator: "\n") puts a newline between each two lines and none after the last.
Step by step
- Create
linesas an empty array of strings, withvar, because it grows. An array declared withletcan't take new elements. - Create
totalas avarstarting at 0. It changes with every item. - Loop over
items.indices. For four items,itakes the values 0, 1, 2 and 3. Using the sameifor all three arrays is what keeps each name matched with its own price and quantity. - Compute
subtotalinside the loop:prices[i] * quantities[i]. It is alet, because it never changes within one pass. - Add it to
totalwith+=. - Append the item's line to
lines. The line is a single string literal with three interpolations: the name, the quantity and the subtotal. Thexand the$are plain characters in the literal. - After the loop, append the
Totalline. It must sit outside the braces. Inside them it would be added once per item. - Create
resultwithlines.joined(separator: "\n"). - Print
result.
The solution in Swift
let items = ["Shirt", "Pants", "Shoes", "Hat"]
let prices = [25, 40, 60, 15]
let quantities = [2, 1, 1, 3]
var lines = [String]()
var total = 0
for i in items.indices {
let subtotal = prices[i] * quantities[i]
total += subtotal
lines.append("\(items[i]) x\(quantities[i]): $\(subtotal)")
}
lines.append("Total: $\(total)")
let result = lines.joined(separator: "\n")
print(result)
The Swift details worth knowing:
[String]()and type inference. An empty array literal[]has no element type to infer, so[String]()states it. The three starter arrays need no annotation, because Swift reads their types from the values:[String]and two[Int].items.indices. It is the range of valid positions,0..<4here. Swift has no C-stylefor (i = 0; ...)loop, and writing0..<items.countwould give the same positions. The loop variableiis a constant inside the body, so the body can read it but can't change it.- Interpolation can hold any expression.
\(items[i])reads an array element inside the string, and\(quantities[i])converts anIntto text on the way. There is no separate conversion step. - Arrays are value types.
lines.appendchanges the variablelinesitself, which is why it needsvar. Declared withlet, the same call would be a compile error. Intarithmetic traps on overflow.prices[i] * quantities[i]uses 64-bit integers, so realistic prices never come close. A product beyond that range would stop the program instead of wrapping silently.
Edge cases and common mistakes
- Arrays of different lengths. The loop runs over the positions of
items. Ifpricesorquantitieswere shorter, reading positioniwould be out of range, and a Swift program crashes on that instead of returning a default value. - An empty cart. With empty arrays the loop body never runs,
totalstays 0, and the output is the single lineTotal: $0. - The total line inside the loop. It would print a Total line for every item. It belongs after the closing brace.
- Using the price instead of the subtotal in the line.
Shirt x2: $25shows the unit price. The line showsprices[i] * quantities[i], which is 50. - Adding the newlines by hand. Writing
"\n"after every line, including the last, adds a blank line at the end of the output, becauseprintadds its own newline.joined(separator:)avoids that. - Declaring
totalinside the loop. A newtotalwould be created on every pass and thrown away, so the final line couldn't see it.
Testing
Try these cart contents in the editor. The outputs come from the reference solution:
items = ["Mug", "Pen"],prices = [7, 2],quantities = [3, 10]printsMug x3: $21,Pen x10: $20andTotal: $41.- Three empty arrays (
[String](),[Int]()and[Int]()) print onlyTotal: $0.
