0
0
Swiftprogramming~15 mins

Why enums are powerful in Swift - See It in Action

Choose your learning style9 modes available
Why enums are powerful in Swift
📖 Scenario: Imagine you are building a simple app that tracks the status of tasks. Each task can be in one of several states like not started, in progress, or completed. Using enums in Swift helps you manage these states clearly and safely.
🎯 Goal: You will create an enum to represent task states, add a variable to hold the current state, write a function to describe the state, and finally print the description. This shows how enums make your code easier to read and less error-prone.
📋 What You'll Learn
Create an enum called TaskState with cases notStarted, inProgress, and completed
Create a variable called currentState of type TaskState and set it to .notStarted
Write a function called describeState that takes a TaskState parameter and returns a String description
Use a switch statement inside describeState to return different messages for each case
Print the description of currentState by calling describeState
💡 Why This Matters
🌍 Real World
Enums are used in apps to represent fixed sets of options like states, modes, or categories. This helps keep code organized and reduces bugs.
💼 Career
Understanding enums is important for Swift developers because they are widely used in iOS and macOS app development to write clean, safe, and maintainable code.
Progress0 / 4 steps
1
Create the enum for task states
Create an enum called TaskState with these exact cases: notStarted, inProgress, and completed
Swift
Need a hint?

Use the enum keyword followed by the name TaskState. Then list the cases inside curly braces.

2
Create a variable for the current state
Create a variable called currentState of type TaskState and set it to .notStarted
Swift
Need a hint?

Declare currentState with var, specify the type TaskState, and assign .notStarted.

3
Write a function to describe the state
Write a function called describeState that takes a parameter state of type TaskState and returns a String. Use a switch statement on state to return these exact strings: "Task not started yet." for .notStarted, "Task is in progress." for .inProgress, and "Task completed!" for .completed
Swift
Need a hint?

Define the function with the correct parameter and return type. Use a switch on state to return the exact strings for each case.

4
Print the description of the current state
Write a print statement that calls describeState with currentState and prints the returned string
Swift
Need a hint?

Call describeState with currentState inside print to show the message.