Challenge - 5 Problems
Raw Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of enum raw value access
What is the output of this Swift code snippet?
Swift
enum Direction: String { case north = "N" case south = "S" case east = "E" case west = "W" } let dir = Direction.east print(dir.rawValue)
Attempts:
2 left
💡 Hint
Check the raw value assigned to the case east.
✗ Incorrect
The enum Direction has raw values of type String. The case east is assigned the raw value "E". Accessing dir.rawValue prints "E".
❓ Predict Output
intermediate2:00remaining
Raw value default assignment for Int enums
What will be printed by this Swift code?
Swift
enum Weekday: Int { case monday = 1 case tuesday case wednesday } print(Weekday.tuesday.rawValue)
Attempts:
2 left
💡 Hint
Int raw values auto-increment from the first assigned value.
✗ Incorrect
Since monday is assigned 1, tuesday gets 2 automatically, so printing rawValue of tuesday outputs 2.
❓ Predict Output
advanced2:30remaining
Using rawValue initializer with valid and invalid values
What is the output of this Swift code?
Swift
enum StatusCode: Int { case success = 200 case notFound = 404 case serverError = 500 } if let status = StatusCode(rawValue: 404) { print("Found: \(status)") } else { print("Not found") } if let status = StatusCode(rawValue: 201) { print("Found: \(status)") } else { print("Not found") }
Attempts:
2 left
💡 Hint
rawValue initializer returns nil if no matching case exists.
✗ Incorrect
StatusCode(rawValue: 404) matches notFound case, so prints Found: notFound. 201 does not match any case, so prints Not found.
❓ Predict Output
advanced3:00remaining
Raw values with mixed types in enum
What error or output does this Swift code produce?
Swift
enum MixedRaw: RawRepresentable { case intCase(Int) case stringCase(String) var rawValue: Any { switch self { case .intCase(let value): return value case .stringCase(let value): return value } } init?(rawValue: Any) { if let intValue = rawValue as? Int { self = .intCase(intValue) } else if let stringValue = rawValue as? String { self = .stringCase(stringValue) } else { return nil } } } let a = MixedRaw(rawValue: 10) print(a?.rawValue ?? "nil")
Attempts:
2 left
💡 Hint
Swift enums with associated values cannot have raw values.
✗ Incorrect
Swift does not allow enums with associated values to have raw values. This code will not compile.
🧠 Conceptual
expert2:30remaining
Raw value uniqueness enforcement
What happens if you define a Swift enum with duplicate raw values like this?
Swift
enum Color: String { case red = "R" case green = "G" case blue = "R" }
Attempts:
2 left
💡 Hint
Raw values must be unique in Swift enums.
✗ Incorrect
Swift requires raw values to be unique. Duplicate raw values cause a compile-time error.