Switch over an enum with associated values using value binding and a where clause
A Transaction enum carries associated values. Implement describe(_:) so it returns a human-readable string for each kind of transaction.
Requirements:
- Bind the associated values with
case let— do not read them after the fact. - Use at least one
whereclause to give large deposits (amount > 1000) a distinct message. - Rely on exhaustiveness — do not add a
defaultbranch.
enum Transaction {
case deposit(amount: Int)
case withdrawal(amount: Int)
case transfer(amount: Int, to: String)
}
func describe(_ t: Transaction) -> String {
// your code here
}
Write the implementation.
Match each case with value binding — case let .deposit(amount) — and add a where guard for a refined branch, e.g. case let .deposit(a) where a > 1000. Since the enum is finite, an exhaustive switch needs no default and flags any unhandled new case.
- ✗Thinking associated values cannot be bound directly in the
casepattern - ✗Believing an exhaustive enum
switchstill needs adefault - ✗Misplacing the
whereclause or treating it as a loop
- →What does the compiler do when you add a case to an exhaustively-switched enum?
- →How does
case letdiffer from binding each associated value individually?
Bind each case's payload with case let and refine one branch with where. All three cases are handled, so no default is needed — and if someone later adds a case, the compiler will error on this switch until it is handled too.
func describe(_ t: Transaction) -> String {
switch t {
case let .deposit(a) where a > 1000:
return "Large deposit of \(a)"
case let .deposit(a):
return "Deposit of \(a)"
case let .withdrawal(a):
return "Withdrawal of \(a)"
case let .transfer(a, to):
return "Transfer of \(a) to \(to)"
}
}
The where branch must precede the plain .deposit branch — switch picks the first matching case top to bottom, so the more specific pattern goes first.