0
0
Swiftprogramming~10 mins

Enum with switch pattern matching 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 define an enum named Direction.

Swift
enum Direction {
    case [1]
    case south
    case east
    case west
}
Drag options to blanks, or click blank then click option'
Anorth
Bleft
Cup
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Using a direction name not listed in the enum cases.
Adding spaces or special characters in the case name.
2fill in blank
medium

Complete the switch statement to handle the Direction enum.

Swift
func describe(direction: Direction) -> String {
    switch direction {
    case [1]:
        return "Going north"
    default:
        return "Other direction"
    }
}
Drag options to blanks, or click blank then click option'
Anorth
Bwest
Ceast
Dsouth
Attempts:
3 left
💡 Hint
Common Mistakes
Using a case that does not exist in the enum.
Forgetting to match the case exactly.
3fill in blank
hard

Fix the error in the switch statement to correctly match the enum cases.

Swift
func action(for direction: Direction) -> String {
    switch direction {
    case .[1]:
        return "Move up"
    case .south:
        return "Move down"
    default:
        return "Stay still"
    }
}
Drag options to blanks, or click blank then click option'
Aleft
Bup
Cnorth
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Using a case name not defined in the enum.
Omitting the dot before the case name.
4fill in blank
hard

Fill both blanks to create a switch that returns a message for east and west directions.

Swift
func directionMessage(_ dir: Direction) -> String {
    switch dir {
    case .[1]:
        return "Heading east"
    case .[2]:
        return "Heading west"
    default:
        return "Unknown direction"
    }
}
Drag options to blanks, or click blank then click option'
Aeast
Bnorth
Cwest
Dsouth
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the east and west cases.
Using cases not defined in the enum.
5fill in blank
hard

Fill all three blanks to create a switch that returns a message for north, south, and other directions.

Swift
func travelAdvice(_ direction: Direction) -> String {
    switch direction {
    case .[1]:
        return "Go forward"
    case .[2]:
        return "Go backward"
    default:
        return "Stay put"
    }
}

let dir = Direction.[3]
print(travelAdvice(dir))
Drag options to blanks, or click blank then click option'
Anorth
Bsouth
Ceast
Dwest
Attempts:
3 left
💡 Hint
Common Mistakes
Using a direction in dir that is not handled explicitly in the switch.
Mixing up the case names in the switch.