Challenge - 5 Problems
Swift Associated Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of enum with associated values
What is the output of this Swift code?
Swift
enum Result { case success(data: String) case failure(errorCode: Int) } let response = Result.success(data: "File loaded") switch response { case .success(let data): print("Success: \(data)") case .failure(let code): print("Error code: \(code)") }
Attempts:
2 left
💡 Hint
Look at which case is assigned to the variable and what the associated value is.
✗ Incorrect
The enum instance is created with the success case and the associated value "File loaded". The switch matches .success and prints the associated data.
❓ Predict Output
intermediate2:00remaining
Extracting multiple associated values
What will this Swift code print?
Swift
enum Shape { case rectangle(width: Int, height: Int) case circle(radius: Int) } let shape = Shape.rectangle(width: 5, height: 10) switch shape { case .rectangle(let w, let h): print("Area: \(w * h)") case .circle(let r): print("Area: \(3.14 * Double(r * r))") }
Attempts:
2 left
💡 Hint
Calculate the area of the rectangle using width and height.
✗ Incorrect
The shape is a rectangle with width 5 and height 10, so area is 5 * 10 = 50.
🔧 Debug
advanced2:00remaining
Identify the error with associated values
What error does this Swift code produce?
Swift
enum Device { case phone(model: String) case tablet } let myDevice = Device.phone(model: "iPhone 14") switch myDevice { case .phone: print("Phone detected") case .tablet: print("Tablet detected") }
Attempts:
2 left
💡 Hint
Check if the associated value is handled in the switch case pattern.
✗ Incorrect
The case .phone has an associated value 'model' but the switch case pattern does not extract it, causing a compiler error.
🧠 Conceptual
advanced1:30remaining
Understanding associated values in enums
Which statement about Swift enums with associated values is true?
Attempts:
2 left
💡 Hint
Think about flexibility of enum cases with associated values.
✗ Incorrect
Swift enums allow each case to have zero or more associated values of any type, and these can differ between cases.
❓ Predict Output
expert2:30remaining
Output of nested associated values in enum
What is the output of this Swift code?
Swift
enum Response { case success(data: (id: Int, message: String)) case failure(error: String) } let result = Response.success(data: (id: 101, message: "OK")) switch result { case .success(let data): print("ID: \(data.id), Message: \(data.message)") case .failure(let error): print("Error: \(error)") }
Attempts:
2 left
💡 Hint
Look at how the tuple is used as an associated value and accessed.
✗ Incorrect
The success case has a tuple with named elements. The switch extracts the tuple and prints its fields.