Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 21 / 68

Writing nil-safe code

This lesson covers handling values safely against nil in Objective-C, with the aim of preventing errors when a value has not been set.

Objective-C represents "no value has been set" with nil. The ?: operator lets you use a substitute value only when something is nil, all on one line.

The sample code displays a substitute string when address is nil by writing address ?: @"No address set". ?: is a ternary operator with the middle part left out.

A common early stumble is that in Objective-C, sending a message to nil is safe — it simply returns nil rather than crashing. That differs from most languages, and not understanding it can hide a problem.

In professional work, allowing for values from a database or an API being empty, and writing nil-safe code, is treated as important for preventing errors.

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

๐Ÿงช This site can't compile or run Objective-C 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)