0
0
Swiftprogramming~5 mins

Optional declaration with ? suffix in Swift

Choose your learning style9 modes available
Introduction

Sometimes a value might be missing or unknown. Using ? lets you say "this value can be there or it can be empty" safely.

When you get data from a form and the user might not fill it in.
When reading from a file or network where the value might not exist.
When a variable might not have a value yet but will later.
When you want to avoid crashes from missing values by checking first.
Syntax
Swift
var variableName: Type?

The ? means the variable can hold a value or be nil (empty).

You must check if it has a value before using it safely.

Examples
This means name can be a string or it can be nil.
Swift
var name: String?
age starts empty but can later hold a number.
Swift
var age: Int? = nil
temperature currently has a value but could be nil later.
Swift
var temperature: Double? = 23.5
Sample Program

This program declares an optional string favoriteColor. It sets it to "Blue". Then it checks if it has a value. If yes, it prints the color. If no, it says no color was set.

Swift
var favoriteColor: String?
favoriteColor = "Blue"

if let color = favoriteColor {
    print("Your favorite color is \(color).")
} else {
    print("You did not set a favorite color.")
}
OutputSuccess
Important Notes

Always unwrap optionals safely using if let or guard let to avoid crashes.

Optionals help prevent errors by forcing you to handle missing values explicitly.

Summary

Use ? after a type to say the value can be missing (nil).

Check if the optional has a value before using it.

This helps your program avoid crashes from unexpected empty values.