0
0
Swiftprogramming~15 mins

Nil represents absence of value in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Nil Represents Absence of Value in Swift
📖 Scenario: Imagine you are creating a simple contact app where some contacts may not have a phone number saved yet. You need to handle the absence of a phone number properly.
🎯 Goal: Learn how to use nil in Swift to represent the absence of a value and safely check for it.
📋 What You'll Learn
Create a variable that can hold a phone number or no value
Assign nil to represent no phone number
Use an if let statement to check if the phone number exists
Print a message showing the phone number or a message saying it is missing
💡 Why This Matters
🌍 Real World
Handling optional values like phone numbers or emails that might not be available yet is common in apps.
💼 Career
Understanding optionals and nil is essential for safe Swift programming and avoiding crashes from missing data.
Progress0 / 4 steps
1
Create an optional String variable for phone number
Create a variable called phoneNumber of type String? and set it to nil to represent no phone number yet.
Swift
Need a hint?

Use String? to make the variable optional, and assign nil to show it has no value.

2
Assign a phone number to the variable
Assign the string "123-456-7890" to the variable phoneNumber.
Swift
Need a hint?

Just set phoneNumber equal to the string value.

3
Use if let to safely unwrap the optional
Use an if let statement with variable number to check if phoneNumber has a value.
Swift
Need a hint?

The if let syntax unwraps the optional safely if it has a value.

4
Print the phone number or a missing message
Inside the if let block, print "Phone number is: \(number)". Add an else block that prints "Phone number is missing".
Swift
Need a hint?

Use print inside both if and else blocks to show the correct message.