Challenge - 5 Problems
Enum Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What is the output of this Swift enum with associated values?
Consider this Swift code that uses an enum with associated values. What will be printed when the code runs?
iOS Swift
enum Device {
case iPhone(model: String)
case iPad(model: String)
}
let myDevice = Device.iPhone(model: "13 Pro")
switch myDevice {
case .iPhone(let model):
print("Using iPhone model: \(model)")
case .iPad(let model):
print("Using iPad model: \(model)")
}Attempts:
2 left
💡 Hint
Look at which case is assigned to myDevice and how the switch extracts the associated value.
✗ Incorrect
The enum instance is created as .iPhone with model "13 Pro". The switch matches .iPhone and prints the model string.
🧠 Conceptual
intermediate1:30remaining
How many associated values does this enum case have?
Look at this Swift enum case declaration. How many associated values does the case 'message' have?
iOS Swift
enum Notification {
case message(sender: String, content: String)
case alert(title: String)
}Attempts:
2 left
💡 Hint
Count the parameters inside the parentheses after the case name.
✗ Incorrect
The 'message' case has two associated values: sender and content, both Strings.
📝 Syntax
advanced2:00remaining
Which option correctly creates an enum instance with associated values?
Given this enum, which code correctly creates an instance of the 'status' case with associated values?
iOS Swift
enum Network {
case status(code: Int, message: String)
case disconnected
}Attempts:
2 left
💡 Hint
Remember the syntax for creating enum cases with named associated values.
✗ Incorrect
Option A uses the correct syntax with parameter labels and values matching the enum definition.
❓ lifecycle
advanced1:30remaining
What happens if you forget to handle an enum case with associated values in a switch?
Consider this code snippet. What error or behavior occurs if the switch does not handle all enum cases?
iOS Swift
enum Action {
case start(time: Int)
case stop
}
let action = Action.start(time: 10)
switch action {
case .stop:
print("Stopped")
}Attempts:
2 left
💡 Hint
Swift requires all enum cases to be handled or a default case provided.
✗ Incorrect
The switch is not exhaustive because it misses the 'start' case, so the compiler raises an error.
🔧 Debug
expert2:30remaining
Why does this code cause a compile error?
Examine this Swift enum and usage. Why does the compiler report an error?
iOS Swift
enum Result {
case success(data: String)
case failure(error: String)
}
let outcome = Result.success("Done")
switch outcome {
case .success:
print("Success")
case .failure(let error):
print("Error: \(error)")
}Attempts:
2 left
💡 Hint
Check how the '.success' case is matched and if it extracts the associated value.
✗ Incorrect
The '.success' case has an associated value but the switch does not extract it, causing a compile error.