Swift 101 - nil
This is a super quick blog to go over the Swift keyword -
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
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
Bool) and a question mark
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.
Swift is the safest
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.
Get the playground for this blog here.