Introducing nil

Sometimes, it’s useful to have a value that represents nothing at all. Imagine a scenario where you need to refer to a person’s identifying information; you want to store the person’s name, age and occupation. Name and age are both things that must have a value — everyone has them. But not everyone is employed, so the absence of a value for occupation is something you need to be able to handle.

Without knowing about optionals, this is how you might represent the person’s name, age and occupation:

var name = "Matt Galloway" var age = 30

var occupation = "Software Developer & Author"

But what if I become unemployed? Maybe I’ve won the lottery and want to give up work altogether (I wish!). This is when it would be useful to be able to refer to the absence of a value.

Why couldn’t you just use an empty string? You could, but optionals are a much

better solution. Read on to see why.

results matching ""

    No results matching ""