Swift 101 - nil

This is a super quick blog to go over the Swift keyword - nil.

nil is described in the Apple docs as:

meaning “the absence of a valid object.”

Not the easiest thing to understand if you’re starting out, right?

If you’re new to programming nil simply means that a variable (sometimes called an object) is empty and has no value assigned.

If you have a background in programming nil can be thought of best as a like-for-like replacement for null.

The Apple docs go on to say:

nil cannot be used with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type

Again, not particularly easy to digest. But here Apple are saying that a variable can only be assigned nil if you as the programmer have said that’s OK. You do that by making a variable nillable, sometimes known as optional. You can learn more about what optionals mean here.

Nillable variables must be defined with both a type (like String, Int or Bool) and a question mark ?.

For example:

var notNillableInt: Int = 1 // The key bit here is `: Int`, note that there is no `?`
var nillableInt: Int? //This variable can be assigned nil, here or in the future.

 Takeaway Tip

Swift is the safest nil/null language I’ve used and the compiler does a lot to remind you when you have said something is potentially nil. Listen to it and think carefully about how a variable is set or changed over time.

An image showing a non nillable variable being assigned nil

Get the playground for this blog here.

Happy Swifting!


Now read this

Swift 101 - let vs var

Welcome, to the first blog in my Swift 101 series! Today I’ll be explaining the difference between let and var, two fundamental keywords in the Swift programming language. If you’re just getting started with Swift this is a great place... Continue →