Back to questions
JuniorTheoryCommon
What does the program print?
enum Category: CaseIterable { case food, taxi }
struct Expense {
let category: Category
let cost: Double
}
let ride = Expense(category: .taxi, cost: 3.5)
let lunch = Expense(category: .food, cost: 2)
var totals: [Category: Double] = [:]
for e in [ride, lunch, ride] {
totals[e.category, default: 0] += e.cost
}
print(Category.allCases.map { totals[$0, default: 0] })[2.0, 7.0]
- Expecting
[7.0, 2.0]: thinking the totals keep the order in which the categories first appeared.mapwalksallCases, which listsfoodfirst, as declared. - Expecting a compile error: thinking an enum must be marked
Hashableto be a dictionary key. Swift makes an enum without associated valuesHashableby itself.
- What does the program print if
taxiis declared beforefood? - Why does
totals.keys.sorted()not compile here, and how else can the totals be printed in a fixed order?