0
0
Swiftprogramming~15 mins

Switch must be exhaustive in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Switch Must Be Exhaustive
📖 Scenario: Imagine you are building a simple app that shows different messages based on the weather condition. You want to use a switch statement to handle all possible weather types.
🎯 Goal: Create a switch statement in Swift that covers all cases of a weather enum without missing any. This will teach you how to make your switch statements exhaustive, so your program handles every possible case safely.
📋 What You'll Learn
Create an enum called Weather with cases sunny, rainy, and cloudy
Create a variable called today and set it to Weather.sunny
Write a switch statement on today that handles all cases of Weather
Print a different message for each weather case
💡 Why This Matters
🌍 Real World
Handling all possible cases in a switch statement helps avoid bugs and crashes in apps that depend on different states or types.
💼 Career
Many programming jobs require writing safe and complete switch statements, especially when working with enums or similar types.
Progress0 / 4 steps
1
Create the Weather enum
Create an enum called Weather with these exact cases: sunny, rainy, and cloudy.
Swift
Need a hint?
Use the enum keyword to define Weather and list all cases exactly.
2
Create the today variable
Create a variable called today and set it to Weather.sunny.
Swift
Need a hint?
Use var today = Weather.sunny to create the variable.
3
Write the exhaustive switch statement
Write a switch statement on today that handles all cases: sunny, rainy, and cloudy. For each case, assign a message string describing the weather to a variable called message.
Swift
Need a hint?
Use switch today { case .sunny: ... case .rainy: ... case .cloudy: ... } and assign messages to message.
4
Print the message
Write a print statement to display the message variable.
Swift
Need a hint?
Use print(message) to show the message on the screen.