Ad space (banner)
๐ŸฆSwift Lessons
Lesson 21 / 68

Optionals (Writing nil-Safe Code)

In this lesson you will learn nil-safe code in Swift with Optionals, and how to avoid errors when a value does not exist. This is for anyone searching for "Swift Optional nil how to use".

Swift expresses "there may be no value" with an Optional (a ? after the type name). ?? supplies a default only when the value is nil.

The sample code writes address ?? "No address set" against a variable declared as let address: String? = nil, showing a replacement string when there is no value. You can see that name, which does hold a value, is used as-is.

A common stumbling block for beginners is trying to use an Optional value directly and hitting an error. Optionals let the compiler check for the possibility of nil, and the if let and guard let constructs unwrap them safely while you carry on.

In real-world development, allowing for values from a database or an API being empty, and writing nil-safe code with Optionals to head off errors, is taken seriously.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)