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 initiallyAssign a real middle name string to
middleNameUse optional binding with
if let to safely unwrap and print the middle namePrint 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