0
0
Swiftprogramming~15 mins

Optional declaration with ? suffix in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Optional Declaration with ? Suffix in Swift
📖 Scenario: Imagine you are creating a simple contact app. Sometimes, a contact might have a middle name, but sometimes they might not. You want to store this information safely without causing errors.
🎯 Goal: You will create a Swift program that uses optional declaration with the ? suffix to handle a contact's middle name, which might or might not be present.
📋 What You'll Learn
Create a variable called middleName declared as an optional String?
Assign nil to middleName initially
Assign a real middle name string to middleName
Use optional binding with if let to safely unwrap and print the middle name
Print a message if the middle name is not available
💡 Why This Matters
🌍 Real World
Optional variables are useful when some information might be missing, like a middle name or a phone number in a contact app.
💼 Career
Understanding optionals is essential for Swift developers to write safe code that avoids crashes from missing values.
Progress0 / 4 steps
1
Declare an optional variable with ? suffix
Create a variable called middleName of type String? and set it to nil.
Swift
Need a hint?

Use var middleName: String? = nil to declare an optional string variable that starts empty.

2
Assign a value to the optional variable
Assign the string "James" to the variable middleName.
Swift
Need a hint?

Just write middleName = "James" to give the optional a real value.

3
Use optional binding to safely unwrap
Use if let with a constant called name to unwrap middleName and print "Middle name is: \(name)" inside the block.
Swift
Need a hint?

Use if let name = middleName { ... } to safely check if middleName has a value.

4
Add else to handle nil case and print result
Add an else block to the if let statement that prints "No middle name provided" when middleName is nil. Run the program to see the output.
Swift
Need a hint?

Use else { print("No middle name provided") } to handle the case when middleName is nil.