Consider this Swift code using enums with associated values. What will it print?
enum Device { case iPhone(model: String) case iPad(model: String) case mac } let myDevice = Device.iPhone(model: "13 Pro") switch myDevice { case .iPhone(let model): print("iPhone model: \(model)") case .iPad(let model): print("iPad model: \(model)") case .mac: print("Mac computer") }
Look at the enum case used to create myDevice and how the switch matches it.
The enum Device has cases with associated values. The instance myDevice is created as .iPhone(model: "13 Pro"). The switch matches the .iPhone case and prints the model.
Which of the following best explains why enums with associated values are powerful in Swift?
Think about how enums can hold different kinds of data in one type.
Enums with associated values let you store different types of data for each case, which helps organize code and avoid errors by grouping related data clearly.
Examine this Swift code snippet. What error will it cause?
enum Direction { case north case south case east case west } let dir = Direction.north switch dir { case .north: print("Going north") case .south: print("Going south") case .east: print("Going east") // Missing case for .west }
Swift requires switch statements on enums to cover all cases or have a default.
The switch statement does not handle the .west case, so the compiler reports a non-exhaustive switch error.
Given this Swift enum and array, how many elements does allCases contain?
enum Fruit: CaseIterable { case apple case banana case cherry } let allFruits = Fruit.allCases print(allFruits.count)
Look at how many cases the enum has and what CaseIterable does.
The enum Fruit has three cases. Conforming to CaseIterable automatically creates allCases with all enum cases, so the count is 3.
Consider this Swift code using an indirect enum for recursive data. What will it print?
indirect enum ArithmeticExpression { case number(Int) case addition(ArithmeticExpression, ArithmeticExpression) case multiplication(ArithmeticExpression, ArithmeticExpression) } func evaluate(_ expr: ArithmeticExpression) -> Int { switch expr { case .number(let value): return value case .addition(let left, let right): return evaluate(left) + evaluate(right) case .multiplication(let left, let right): return evaluate(left) * evaluate(right) } } let expr = ArithmeticExpression.addition( .number(2), .multiplication( .number(3), .number(4) ) ) print(evaluate(expr))
Calculate the expression step by step: 2 + (3 * 4).
The expression represents 2 + (3 * 4). Multiplication happens first: 3 * 4 = 12. Then addition: 2 + 12 = 14.