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