Optionals in Swift

Sudha Chandran B C
Swiftable
Published in
4 min readAug 30, 2023

--

Optionals are an essential concept in programming, especially in languages like Swift, Kotlin, and others that aim to prevent null pointer exceptions and provide safer handling of nullable values.

The primary purpose of optionals is to improve code safety by explicitly indicating the possibility of missing values, reducing the chances of runtime crashes due to null pointer exceptions.

Intro:

Swift makes a very clear distinction between “no value” and all other values. “No value” is referred to as nil and is a different type from all others.

If you want a variable to be allowed sometimes to be nil, you make it an optional variable.

Only optional variables are allowed to be set to nil. If a variable isn’t defined as optional, it’s not allowed to be set to the nil value:

var aNonOptionalInteger = 42 // Nonoptional (regular), NOT allowed to be nil
aNonOptionalInteger = nil // ERROR: only optional values can be nilss

You can check to see if an optional variable has a value by using an if statement:

Note that if you unwrap an optional variable and it has no value, your program will throw a runtime error and crash

Unwrapping:

--

--

Sudha Chandran B C
Swiftable

An iOS Developer, mother of twin boys. Writes about iOS, Swift, Interview prep guides and Productivity tips, Positivity, Life and experiences.