Start learning free

LESSON 193 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in Swift: Cart Sum with a for Loop

Practice Read the full explanation

Use a for loop over parallel arrays to compute a running total across several items.

You start with:

        let items = ["Shirt", "Pants", "Shoes", "Hat"]
        let prices = [25, 40, 60, 15]
        let quantities = [2, 1, 1, 3]

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result, then print it with print(result).

Use var lines = [String]() and var total = 0 before the loop, then append each formatted line.

Call lines.joined(separator: "\n") at the end.

        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)

STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in Swift, explained

    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

    1. Create lines as an empty array of strings, with var, because it grows. An array declared with let can't take new elements.
    2. Create total as a var starting at 0. It changes with every item.
    3. Loop over items.indices. For four items, i takes the values 0, 1, 2 and 3. Using the same i for all three arrays is what keeps each name matched with its own price and quantity.
    4. Compute subtotal inside the loop: prices[i] * quantities[i]. It is a let, because it never changes within one pass.
    5. Add it to total with +=.
    6. Append the item's line to lines. The line is a single string literal with three interpolations: the name, the quantity and the subtotal. The x and the $ are plain characters in the literal.
    7. After the loop, append the Total line. It must sit outside the braces. Inside them it would be added once per item.
    8. Create result with lines.joined(separator: "\n").
    9. 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..<4 here. Swift has no C-style for (i = 0; ...) loop, and writing 0..<items.count would give the same positions. The loop variable i is 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 an Int to text on the way. There is no separate conversion step.
    • Arrays are value types. lines.append changes the variable lines itself, which is why it needs var. Declared with let, the same call would be a compile error.
    • Int arithmetic 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. If prices or quantities were shorter, reading position i would 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, total stays 0, and the output is the single line Total: $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: $25 shows the unit price. The line shows prices[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, because print adds its own newline. joined(separator:) avoids that.
    • Declaring total inside the loop. A new total would 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] prints Mug x3: $21, Pen x10: $20 and Total: $41.
    • Three empty arrays ([String](), [Int]() and [Int]()) print only Total: $0.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free