0
0
Swiftprogramming~30 mins

Nil coalescing operator deep usage in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Nil coalescing operator deep usage
📖 Scenario: You are building a simple user profile display system. Sometimes, some user information might be missing (nil). You want to use the nil coalescing operator to provide default values in a clean and readable way.
🎯 Goal: Learn how to use the nil coalescing operator ?? deeply in Swift to handle optional values and provide fallback defaults.
📋 What You'll Learn
Create a dictionary called userProfile with optional values for keys "name", "age", and "city".
Create a constant called defaultCity with the value "Unknown City".
Use the nil coalescing operator ?? to create a constant displayCity that uses userProfile["city"] or falls back to defaultCity.
Print the displayCity value.
💡 Why This Matters
🌍 Real World
Handling missing or optional data is common in apps that get data from the internet or user input. Using the nil coalescing operator helps keep code clean and safe.
💼 Career
Swift developers often work with optionals. Mastering nil coalescing is essential for writing robust iOS apps that handle missing data gracefully.
Progress0 / 4 steps
1
Create the user profile dictionary
Create a dictionary called userProfile with these exact entries: "name": "Alice", "age": nil, and "city": nil. Use type [String: String?].
Swift
Need a hint?

Use a dictionary with optional String values. Assign nil to age and city.

2
Create the default city constant
Create a constant called defaultCity and set it to the string "Unknown City".
Swift
Need a hint?

Use let to create a constant string.

3
Use nil coalescing operator to get display city
Create a constant called displayCity that uses the nil coalescing operator ?? to get userProfile["city"] or fall back to defaultCity. Since userProfile["city"] is an optional optional (String??), unwrap it safely using ?? twice.
Swift
Need a hint?

Remember that userProfile["city"] returns String??. Use ?? twice to unwrap.

4
Print the display city
Write a print statement to display the value of displayCity.
Swift
Need a hint?

Use print(displayCity) to show the result.