0
0
Swiftprogramming~15 mins

Associated values per case in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Associated Values in Swift Enums
📖 Scenario: Imagine you are building a simple app to track different types of notifications a user can receive. Each notification type can carry extra information.
🎯 Goal: You will create an enum with associated values to represent different notification types and then write code to handle them.
📋 What You'll Learn
Create an enum called Notification with cases that have associated values
Add a variable to hold a sample notification
Use a switch statement to extract and print the associated values
Print the final message describing the notification
💡 Why This Matters
🌍 Real World
Enums with associated values are useful to represent different types of data that share a category but carry extra information, like notifications, messages, or API responses.
💼 Career
Understanding enums with associated values is important for Swift developers building iOS apps, as it helps write clear and safe code for handling varied data types.
Progress0 / 4 steps
1
Create the Notification enum with associated values
Create an enum called Notification with these cases and associated values exactly: message(String), friendRequest(from: String), and photoLike(photoID: Int, liker: String).
Swift
Need a hint?

Use enum keyword and define cases with parentheses for associated values.

2
Create a variable with a sample notification
Create a variable called notification and assign it the Notification.friendRequest(from: "Alice") value.
Swift
Need a hint?

Use var notification = Notification.friendRequest(from: "Alice") exactly.

3
Use a switch to handle the notification and extract associated values
Write a switch statement on notification with cases for .message(let text), .friendRequest(let from), and .photoLike(let photoID, let liker). Inside each case, create a variable description with a string describing the notification using the associated values.
Swift
Need a hint?

Use switch notification and pattern match each case with let to get associated values.

4
Print the notification description
Write a print statement to display the description variable.
Swift
Need a hint?

Use print(description) to show the message.