Start learning free

LESSON 194 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in Swift: Coupon Codes with a Dictionary

Practice Read the full explanation

Use a map as a fast lookup table for coupon discounts.

You start with:

        let subtotal = 100
        let coupon = "SAVE20"
        let coupons = ["SAVE10": 10, "SAVE20": 20, "SAVE50": 50]

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with print(result).

Use coupons[coupon, default: 0]: it returns the value if the key is present, or 0 if it is missing.

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

        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)

STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in Swift, explained

    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

    1. Look the coupon up with a default. coupons[coupon, default: 0] returns the stored discount when the key exists and 0 when it doesn't. The result is a plain Int, not an optional, so it can be used in arithmetic right away.
    2. Compute total as subtotal - discount. An unknown code gives a discount of 0, so this line needs no special case.
    3. Build result as "Total: $\(total)". Interpolation converts the integer to text inside the literal.
    4. 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 String keys and Int values, so coupons is a [String: Int]. Declared with let, it can't be changed afterwards, which suits a fixed table of coupons.
    • The plain subscript returns an optional. coupons["BAD"] has the type Int? and evaluates to nil when the key is missing. The default: form is a different subscript that always returns an Int. It does not insert the default into the dictionary, so coupons stays the same after the lookup.
    • Other ways to write the same thing. coupons[coupon] ?? 0 gives the same value, using the nil-coalescing operator on the optional. Unwrapping with coupons[coupon]! would crash for an unknown code, so it fits only when the key is certain to exist.
    • Keys are compared exactly. A String key 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 is Total: $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 an Int and an Int? 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 SAVE50 on a subtotal of 30, the total is negative and the line reads Total: $-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:

    • SAVE10 on 100 prints Total: $90.
    • SAVE50 on 100 prints Total: $50.
    • save20 on 100 prints Total: $100.
    • An empty coupon on 100 prints Total: $100.
    • SAVE50 on 30 prints Total: $-20.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free