0
0
Swiftprogramming~15 mins

Enum with switch pattern matching in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Enum with switch pattern matching
📖 Scenario: Imagine you are building a simple app that shows different messages based on the weather condition. The weather can be sunny, rainy, or snowy.
🎯 Goal: You will create an enum to represent weather conditions, then use a switch statement with pattern matching to print the correct message for each weather type.
📋 What You'll Learn
Create an enum called Weather with cases sunny, rainy, and snowy
Create a variable called today and assign it the Weather.sunny value
Use a switch statement on today with cases for each weather type
Print a message inside each case describing the weather
💡 Why This Matters
🌍 Real World
Enums and switch statements are used in apps to handle different states or options clearly and safely.
💼 Career
Understanding enums and pattern matching is important for Swift developers building iOS apps with clear and maintainable code.
Progress0 / 4 steps
1
Create the Weather enum
Create an enum called Weather with three cases: sunny, rainy, and snowy.
Swift
Need a hint?

Use the enum keyword followed by the name Weather. Inside curly braces, list the cases with the case keyword.

2
Create a variable for today's weather
Create a variable called today and assign it the value Weather.sunny.
Swift
Need a hint?

Use var today = Weather.sunny to create the variable.

3
Use switch to match the weather
Write a switch statement on the variable today. Add cases for .sunny, .rainy, and .snowy. Inside each case, write a print statement with a message describing the weather, for example, print("It's sunny today!").
Swift
Need a hint?

Use switch today { case .sunny: ... } and print messages inside each case.

4
Print the weather message
Run the program to print the message for today's weather. The output should be exactly: It's sunny today!
Swift
Need a hint?

Make sure you run the program and see the message printed exactly as shown.