Start learning free

LESSON 165 OF 415 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 - Free Shipping in Swift

Practice

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

    Shopping Cart V3 in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free