0
0
Swiftprogramming~10 mins

Iterating enum cases with CaseIterable in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the enum conform to CaseIterable.

Swift
enum Direction: [1] {
    case north, south, east, west
}
Drag options to blanks, or click blank then click option'
ACaseIterable
BCodable
CEquatable
DHashable
Attempts:
3 left
💡 Hint
Common Mistakes
Using other protocols like Codable or Equatable which do not provide case iteration.
2fill in blank
medium

Complete the code to print all cases of the enum.

Swift
for direction in Direction.[1] {
    print(direction)
}
Drag options to blanks, or click blank then click option'
Acases
Bvalues
CallCases
Delements
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect property names like 'cases' or 'values' which do not exist.
3fill in blank
hard

Fix the error in the code to correctly iterate over enum cases.

Swift
enum Color: CaseIterable {
    case red, green, blue
}

for color in Color.[1]() {
    print(color)
}
Drag options to blanks, or click blank then click option'
AallCases
BallCases()
Ccases
Dall_cases
Attempts:
3 left
💡 Hint
Common Mistakes
Calling allCases with parentheses like a function.
4fill in blank
hard

Fill both blanks to create a dictionary with enum case names as keys and raw values as values.

Swift
enum Fruit: String, CaseIterable {
    case apple = "Red"
    case banana = "Yellow"
    case grape = "Purple"
}

let fruitColors = [[1]: [2] for fruit in Fruit.allCases]
Drag options to blanks, or click blank then click option'
Afruit.rawValue
Bfruit
Cfruit.name
Dfruit.description
Attempts:
3 left
💡 Hint
Common Mistakes
Using fruit.name or fruit.description which do not exist.
5fill in blank
hard

Fill all three blanks to filter enum cases with raw value length greater than 5 and create a list of their names.

Swift
enum Vehicle: String, CaseIterable {
    case car = "Auto"
    case motorcycle = "Motorcycle"
    case bicycle = "Bike"
    case airplane = "Airplane"
}

let longNames = [[1] for vehicle in Vehicle.allCases if [2].[3] > 5]
Drag options to blanks, or click blank then click option'
Avehicle.rawValue
Bcount
Cvehicle
Attempts:
3 left
💡 Hint
Common Mistakes
Using the enum case itself instead of raw values.
Checking length on the enum case instead of the raw value.