Problem overview
A shopper types a coupon code, and the program takes the matching amount off the subtotal. You start with subtotal (100), the typed coupon ("SAVE20") and a dictionary coupons that maps each valid code to its discount in dollars: SAVE10 is 10, SAVE20 is 20 and SAVE50 is 50.
The program looks the code up. A known code gives its discount, and an unknown code gives 0. Then it computes total = subtotal - discount and prints one line. For SAVE20 on a subtotal of 100:
Total: $80
An unknown code takes nothing off, so the line would read Total: $100.
Approach: a dictionary as a lookup table
You could compare the code against each known string with a chain of if and else if, but every new coupon would need another branch. A dictionary keeps the data apart from the logic: the codes and amounts live in one literal, and the lookup is a single expression. A dictionary finds a key in constant time on average, however many coupons it holds.
The one question is what a missing code should do. In Swift, reading a key that isn't in a dictionary doesn't crash and doesn't give 0. It gives nil, which is a "no value" result that the type system tracks. The lesson avoids handling that optional by asking the dictionary for a default.
Step by step
- Look the coupon up with a default.
coupons[coupon, default: 0]returns the stored discount when the key exists and0when it doesn't. The result is a plainInt, not an optional, so it can be used in arithmetic right away. - Compute
totalassubtotal - discount. An unknown code gives a discount of 0, so this line needs no special case. - Build
resultas"Total: $\(total)". Interpolation converts the integer to text inside the literal. - Print
result.
The solution in Swift
let subtotal = 100
let coupon = "SAVE20"
let coupons = ["SAVE10": 10, "SAVE20": 20, "SAVE50": 50]
let discount = coupons[coupon, default: 0]
let total = subtotal - discount
let result = "Total: $\(total)"
print(result)
Swift details in this short program:
- The dictionary type is inferred. The literal has
Stringkeys andIntvalues, socouponsis a[String: Int]. Declared withlet, it can't be changed afterwards, which suits a fixed table of coupons. - The plain subscript returns an optional.
coupons["BAD"]has the typeInt?and evaluates tonilwhen the key is missing. Thedefault:form is a different subscript that always returns anInt. It does not insert the default into the dictionary, socouponsstays the same after the lookup. - Other ways to write the same thing.
coupons[coupon] ?? 0gives the same value, using the nil-coalescing operator on the optional. Unwrapping withcoupons[coupon]!would crash for an unknown code, so it fits only when the key is certain to exist. - Keys are compared exactly. A
Stringkey matches only the same characters in the same case."save20"is a different key from"SAVE20"and counts as unknown.
Edge cases and common mistakes
- An unknown code. A made-up code finds no entry, the discount is 0, and the line is
Total: $100. An empty string behaves the same way. - A different case. With
coupon = "save20"the output isTotal: $100, because dictionary keys are case-sensitive. The program doesn't normalise the text, and the lesson doesn't ask it to. - Using the optional directly. Writing
subtotal - coupons[coupon]without a default doesn't compile, since anIntand anInt?can't be subtracted. The compiler is pointing out that the missing-code case has to be handled somewhere. - Forced unwrapping.
coupons[coupon]!compiles, and works for the starter data, but stops the program as soon as the code is unknown. - A discount larger than the subtotal. The lesson's rules don't cap the discount. With
SAVE50on a subtotal of 30, the total is negative and the line readsTotal: $-20. Clamping the total at 0 would be a separate rule.
Testing
Change subtotal and coupon in the editor. These results come from the reference solution:
SAVE10on 100 printsTotal: $90.SAVE50on 100 printsTotal: $50.save20on 100 printsTotal: $100.- An empty coupon on 100 prints
Total: $100. SAVE50on 30 printsTotal: $-20.
