Start learning free

LESSON 192 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 in Swift: Free Shipping with if/else

Practice Read the full explanation

Use an if/else to decide whether to charge shipping based on a free-shipping threshold.

You start with:

        let subtotal = 75
        let shippingCost = 10
        let freeShippingThreshold = 100

Build:

Subtotal: $75
Shipping: $10
Total: $85

Rules:

  • If subtotal >= freeShippingThreshold, set shipping to 0; otherwise set it to shippingCost.
  • total = subtotal + shipping.
  • Always include all three lines (Subtotal, Shipping, Total). When shipping is free, the line shows $0: for a subtotal of 120 the lines would be Subtotal: $120, Shipping: $0, Total: $120.
  • Join the three lines with a newline "\n" into one string result, then print it with print(result).

Decide shipping in an if/else first, then build the three lines.

Declare var shipping: Int before the if, so it is still visible after the if/else, then assign it in both branches.

Use string interpolation, for example "Total: $\(total)", to embed a number in text.

        let subtotal = 75
        let shippingCost = 10
        let freeShippingThreshold = 100

        var shipping: Int
        if subtotal >= freeShippingThreshold {
            shipping = 0
        } else {
            shipping = shippingCost
        }
        let total = subtotal + shipping
        let line1 = "Subtotal: $\(subtotal)"
        let line2 = "Shipping: $\(shipping)"
        let line3 = "Total: $\(total)"
        let result = line1 + "\n" + line2 + "\n" + line3
        print(result)

STEP 1 OF 11
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V3 in Swift, explained

    Problem overview

    This version of the shopping cart program decides whether an order pays for shipping. You start with three constants: subtotal, the price of the goods; shippingCost, the normal shipping fee; and freeShippingThreshold, the subtotal from which shipping is free. The program prints a three-line receipt: the subtotal, the shipping and the total.

    With a subtotal of 75, a shipping cost of 10 and a threshold of 100, the cart is under the threshold, so it pays for shipping:

    Subtotal: $75
    Shipping: $10
    Total: $85

    A subtotal of 120 is over the threshold. The receipt still has all three lines, but the shipping line shows $0 and the total equals the subtotal.

    Approach: decide first, then print

    The receipt depends on one decision, so make that decision before building any text. An if/else picks the shipping amount: 0 when subtotal >= freeShippingThreshold, otherwise shippingCost. Once shipping is known, the total is a plain addition, and the three lines are the same for every cart. Only the numbers change.

    The program has two paths, and each one ends with shipping holding a number. Everything after the if/else runs the same way on both paths.

    The comparison uses >= rather than >, because "from 100 up" includes a cart worth exactly 100. A subtotal of 100 ships free, and a subtotal of 99 pays 10.

    The threshold and the fee are constants instead of numbers written into the condition, so changing a business rule means editing one line at the top. The rest of the program reads the names and needs no change.

    Step by step

    1. Declare shipping without a value. var shipping: Int reserves the name and its type. Both branches of the if/else will assign it, and because it is declared before the if, it is still visible after the closing brace.
    2. Write the if. Its condition compares subtotal with freeShippingThreshold. Swift doesn't need parentheses around the condition, but it always needs the braces.
    3. Set shipping to 0 inside the if: free shipping costs nothing.
    4. Close that block and add else. In Swift style, } else { sits on one line.
    5. Set shipping to shippingCost inside the else: the cart is under the threshold and pays the normal fee.
    6. Compute total as subtotal + shipping. When shipping is free the added number is 0, so the total equals the subtotal and no special case is needed.
    7. Build the three lines, line1, line2 and line3, each with string interpolation. \(subtotal) inside a string literal turns the number into text, so no conversion call is needed.
    8. Join them into result with "\n" between each two. Three lines need two newlines, and there is none after the last line.
    9. Print result with print(result).

    The solution in Swift

            let subtotal = 75
            let shippingCost = 10
            let freeShippingThreshold = 100
    
            var shipping: Int
            if subtotal >= freeShippingThreshold {
                shipping = 0
            } else {
                shipping = shippingCost
            }
            let total = subtotal + shipping
            let line1 = "Subtotal: $\(subtotal)"
            let line2 = "Shipping: $\(shipping)"
            let line3 = "Total: $\(total)"
            let result = line1 + "\n" + line2 + "\n" + line3
            print(result)
    

    Some Swift details in this code:

    • A declared but unassigned variable. var shipping: Int has no value yet, and Swift refuses to compile any read of it until every path through the if/else has assigned it. Forgetting the else branch would therefore be a compile error, not a silent zero. Because each path assigns shipping exactly once, let shipping: Int works too, and the program prints the same result. The lesson uses var, which also works.
    • The dollar sign is an ordinary character. In "Subtotal: $\(subtotal)", the $ is printed as it is, and the backslash-parenthesis pair starts the interpolation. The number comes out without any formatting, so $85 and not $85.00: these prices are whole numbers of dollars.
    • Interpolation versus +. The three lines are joined with +, which works because all of them are String values. Writing "Total: $" + total with an Int would not compile, as + won't mix String and Int.
    • Constants as the condition. The compiler can see that the starter values are fixed, so it may warn that one branch will never be executed. That is only a warning, and the program still builds and runs. With other starter values the other branch would be the dead one.

    Edge cases and common mistakes

    • A cart exactly on the threshold. With > instead of >=, a subtotal of 100 would pay shipping. With the reference solution it prints Shipping: $0 and Total: $100.
    • Leaving out the shipping line for free carts. The receipt always has three lines. A free cart shows Shipping: $0, so the line is built outside the if/else, from the variable.
    • Printing instead of assigning inside the branches. If each branch printed its own text, the total would be computed in two places. Deciding the number first keeps one copy of the receipt code.
    • A trailing newline in result. print already ends its output with a newline, so adding "\n" after the last line would leave an empty line at the end.

    Testing

    Change subtotal in the editor and compare. These are the outputs of the reference solution:

    • subtotal = 99 prints Subtotal: $99, Shipping: $10, Total: $109.
    • subtotal = 100 prints Subtotal: $100, Shipping: $0, Total: $100.
    • subtotal = 120 prints Subtotal: $120, Shipping: $0, Total: $120.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free