0
0
Swiftprogramming~20 mins

Enum declaration and cases in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Enum Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of enum with raw values
What is the output of this Swift code?
Swift
enum Direction: String {
    case north = "N"
    case south = "S"
    case east = "E"
    case west = "W"
}

let dir = Direction.east
print(dir.rawValue)
A"E"
B"east"
CDirection.east
D"East"
Attempts:
2 left
💡 Hint
Look at the rawValue property of the enum case.
Predict Output
intermediate
2:00remaining
Enum with associated values output
What will this Swift code print?
Swift
enum Result {
    case success(Int)
    case failure(String)
}

let res = Result.failure("Error")
switch res {
case .success(let code):
    print("Success with code \(code)")
case .failure(let message):
    print("Failed: \(message)")
}
AFailed: failure
BFailed: Error
CSuccess with code 0
DSuccess with code Error
Attempts:
2 left
💡 Hint
Check which case is assigned to res and what the associated value is.
🔧 Debug
advanced
2:00remaining
Identify the error in enum declaration
Which option shows the error when compiling this enum declaration?
Swift
enum Color {
    case red
    case green
    case blue
    case yellow = 4
}
AError: Missing comma between cases
BNo error, compiles fine
CError: Enum cases cannot have assigned integer values without raw type
DError: Enum cases must be strings
Attempts:
2 left
💡 Hint
Check if enum has raw type when assigning values to cases.
🧠 Conceptual
advanced
2:00remaining
Number of cases in enum
Given this enum, how many cases does it have?
Swift
enum Weekday {
    case monday, tuesday, wednesday
    case thursday
    case friday, saturday, sunday
}
A7
B5
C6
D3
Attempts:
2 left
💡 Hint
Count all the cases separated by commas and lines.
Predict Output
expert
3:00remaining
Output of enum with indirect recursive case
What does this Swift code print?
Swift
enum ArithmeticExpression {
    case number(Int)
    indirect case addition(ArithmeticExpression, ArithmeticExpression)
}

let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)

func evaluate(_ expr: ArithmeticExpression) -> Int {
    switch expr {
    case .number(let value):
        return value
    case .addition(let left, let right):
        return evaluate(left) + evaluate(right)
    }
}

print(evaluate(sum))
A0
B54
CError: indirect case not allowed
D9
Attempts:
2 left
💡 Hint
Think about how the recursive evaluation adds the numbers.