Back to questions
JuniorTheoryCommon
What does the program print?
enum Order {
case tea
case coffee(cups: Int)
}
func cost(_ order: Order) -> Int {
switch order {
case .tea: return 2
case .coffee(let cups) where cups > 2: return cups * 2
case .coffee(let cups): return cups * 3
}
}
print(cost(.coffee(cups: 2)), cost(.coffee(cups: 4)))6 8
- Expecting
4 8: readingwhereas a remark. A branch withwhereruns only when its condition holds; otherwise theswitchchecks the next branch. - Expecting a compile error because there is no
default: aswitchon an enum compiles once every case has a branch.
- What does the program print if you swap the two
.coffeebranches? - How would you read the number of cups with
if caseinstead of aswitch?