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
- Declare
shippingwithout a value.var shipping: Intreserves the name and its type. Both branches of theif/elsewill assign it, and because it is declared before theif, it is still visible after the closing brace. - Write the
if. Its condition comparessubtotalwithfreeShippingThreshold. Swift doesn't need parentheses around the condition, but it always needs the braces. - Set
shippingto0inside theif: free shipping costs nothing. - Close that block and add
else. In Swift style,} else {sits on one line. - Set
shippingtoshippingCostinside theelse: the cart is under the threshold and pays the normal fee. - Compute
totalassubtotal + shipping. When shipping is free the added number is 0, so the total equals the subtotal and no special case is needed. - Build the three lines,
line1,line2andline3, each with string interpolation.\(subtotal)inside a string literal turns the number into text, so no conversion call is needed. - Join them into
resultwith"\n"between each two. Three lines need two newlines, and there is none after the last line. - Print
resultwithprint(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: Inthas no value yet, and Swift refuses to compile any read of it until every path through theif/elsehas assigned it. Forgetting theelsebranch would therefore be a compile error, not a silent zero. Because each path assignsshippingexactly once,let shipping: Intworks too, and the program prints the same result. The lesson usesvar, 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$85and not$85.00: these prices are whole numbers of dollars. - Interpolation versus
+. The three lines are joined with+, which works because all of them areStringvalues. Writing"Total: $" + totalwith anIntwould not compile, as+won't mixStringandInt. - 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 printsShipping: $0andTotal: $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 theif/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.printalready 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 = 99printsSubtotal: $99,Shipping: $10,Total: $109.subtotal = 100printsSubtotal: $100,Shipping: $0,Total: $100.subtotal = 120printsSubtotal: $120,Shipping: $0,Total: $120.
