0
0
Swiftprogramming~10 mins

Nil coalescing operator (??) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Nil Coalescing Operator (??) in Swift
📖 Scenario: You are creating a simple app that shows user profile information. Sometimes, the user might not provide their nickname. You want to display a default nickname when the user does not have one.
🎯 Goal: Build a Swift program that uses the nil coalescing operator ?? to provide a default nickname when the user's nickname is missing.
📋 What You'll Learn
Create an optional String variable called nickname with the value nil.
Create a constant String called defaultNickname with the value "Guest".
Use the nil coalescing operator ?? to create a constant displayName that uses nickname if it has a value, or defaultNickname if nickname is nil.
Print the value of displayName.
💡 Why This Matters
🌍 Real World
Apps often have optional data from users. The nil coalescing operator helps show default values so the app looks friendly and complete.
💼 Career
Understanding optionals and the nil coalescing operator is essential for Swift developers building safe and user-friendly iOS apps.
Progress0 / 4 steps
1
Create the optional nickname variable
Create an optional String variable called nickname and set it to nil.
Swift
Need a hint?

Use var nickname: String? = nil to create an optional variable with no value.

2
Create the default nickname constant
Create a constant String called defaultNickname and set it to "Guest".
Swift
Need a hint?

Use let defaultNickname = "Guest" to create a constant string.

3
Use the nil coalescing operator to set displayName
Use the nil coalescing operator ?? to create a constant called displayName that uses nickname if it has a value, or defaultNickname if nickname is nil.
Swift
Need a hint?

Use let displayName = nickname ?? defaultNickname to assign the first non-nil value.

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

Use print(displayName) to show the result.