Problem overview
The first version of the shopping cart project prints a tiny receipt for a single item. The starter code defines item ("Coffee Mug"), price (12) and quantity (3). The program computes the total, then builds one string, result, with two lines and prints it:
Coffee Mug x3
Total: $36
The first line is the item name, a space, the letter x and the quantity. The second line is Total: $ followed by price * quantity.
Approach: compute, format each line, then join
The work splits into three small pieces, and each one gets a named constant, so every line of the program does one thing:
- the arithmetic,
total, which is the price of one item repeated once per item bought; - the two text lines,
line1andline2, each a string literal with interpolated values; - the joined text,
result, which isline1, a newline andline2.
Doing the arithmetic before the formatting means the text-building lines contain no calculations, and each row can be read straight off the output it produces.
Step by step
- Create
totalas aletequal toprice * quantity. This is the cost of every mug. - Create
line1: the item name, a space,x, then the quantity. Interpolation puts both values into one literal, and the space before thexis part of the literal. - Create
line2: the labelTotal: $followed by the total, again as one literal with interpolation. - Create
resultby joiningline1, a newline andline2with+. The newline character starts a new row where it sits. - Print
resultwithprint.
The solution in Swift
let item = "Coffee Mug"
let price = 12
let quantity = 3
let total = price * quantity
let line1 = "\(item) x\(quantity)"
let line2 = "Total: $\(total)"
let result = line1 + "\n" + line2
print(result)
The Swift details worth knowing:
- Interpolation converts for you. In
"\(item) x\(quantity)",itemis a string andquantityanInt, and both go in without a conversion call. Thexsits directly after the first hole and directly before the second, with no extra characters. - Numbers don't join to text with
+. Writingitem + " x" + quantitydoesn't compile: the compiler reportsbinary operator '+' cannot be applied to operands of type 'String' and 'Int'. Use interpolation, orString(quantity). - The
$is a normal character. In"Total: $\(total)", the dollar sign is plain text and the interpolation follows it. "\n"is a newline. The two characters in the source, a backslash and ann, become one newline character in the string, so the singleprintshows two rows.- Type inference.
priceandquantityareInts, sototalis anInttoo. Arithmetic between two different numeric types, such as anIntand aDouble, needs an explicit conversion in Swift. - Overflow. An
Intis 64 bits in Swift, so this multiplication has plenty of room. If a product ever did exceed that range, Swift would stop the program with a run-time error, not wrap around.
Edge cases and common mistakes
- Quantity of zero. With
quantity = 0, the receipt readsCoffee Mug x0andTotal: $0. The code needs no special case. - Missing spaces. The row is
Coffee Mug x3: a space between the name and thex, and no space between thexand the number. Check the literal character by character. - Forgetting the newline. Joining
line1 + line2without"\n"puts both rows on one line. - Hard-coding the numbers. Typing
36into the string matches today's data only. Computetotalfrompriceandquantity, and interpolate it. - Printing the rows with two separate calls. That also shows two rows, but the lesson builds a single
resultstring first, and the exercise is about composing it.
Testing
- The starter data prints
Coffee Mug x3andTotal: $36. - With
quantity = 0, it printsCoffee Mug x0andTotal: $0.
