What if your program could safely handle missing information without crashing or confusing you?
Why Optional declaration with ? suffix in Swift? - Purpose & Use Cases
Imagine you are writing a program that asks people for their phone numbers. Some people might not want to share their number. If you try to store every phone number as if it always exists, what do you do when someone doesn't give one?
Without a way to say "this might be missing," your program can crash or give wrong answers. You have to write extra checks everywhere to see if the number is there or not. This makes your code long, confusing, and easy to break.
Using the optional declaration with a ? lets you say, "This value might be there, or it might be missing." Swift helps you handle these cases safely and clearly, so your program won't crash and your code stays neat.
var phoneNumber: String = "" // What if no number? Use empty string or special value if phoneNumber == "" { print("No number provided") }
var phoneNumber: String? if let number = phoneNumber { print("Number is \(number)") } else { print("No number provided") }
It makes your programs safer and easier to understand by clearly showing when a value might be missing.
When building a contact app, some contacts might not have an email or phone number. Using optionals lets you store these contacts without forcing fake or empty values.
Optionals let you represent values that might be missing.
They prevent crashes by forcing you to check for missing values.
Using ? keeps your code clean and safe.