In an earlier article, I defined how variables are outlined in Swift utilizing let and var. Each constants (let
) and variables (var
) in Swift at all times have a kind; it is what makes Swift a strongly typed language.
For instance, we might outline a String
variable like this:
// the compiler will know myString is a String
var myString = "Whats up, world"
// we're explicitly telling the compiler that myString2 is a String
var myString2: String = "Whats up, world"
This fashion of defining variables makes loads of sense when it is potential to right away assign a worth to our variable.
Nonetheless, typically you will write code the place it isn’t potential to assign a worth to your variable instantly. Otherwise you’re working with features which will or might not be capable to return a legitimate worth.
In Swift, we name values that may distiguish betwene having a worth and never having a worth an Optionally available
. Earlier than we dig too deeply into how we work with optionals, let’s discover the distinction between “no worth” and “default” worth in order that we perceive precisely why optionals exist within the first place.
For those who want to study by way of video as a substitute of textual content, take a look at this video on my YouTube channel
The distinction between a default worth and no worth
In programming, working with an idea known as null
or as Swift calls it nil
will usually imply {that a} variable or a operate’s return worth could be “nothing”. There’s loads of technical baggage surrounding the terminology however with the intention to set up working information, we cannot dig into that too deeply.
The vital factor to know right here is that defining an empty String
like this: var myString = ""
defines a String
with a default worth. The worth is empty however the var myString
is holding on to some knowledge that can symbolize an empty String
. Typically it is a completely high quality selection.
Now let’s contemplate a special instance the place a default worth can be rather a lot tougher to outline.
var theUser: Consumer = ???
Our Consumer
object cannot be created with out enter from different sources. And this enter may not be current at the moment that we outline our variable. We’ll want a approach to outline this var theUser
with no knowledge quite than a default worth.
An actual world analogy you would possibly consider is the next. If you sit down at a restaurant for some drinks, you’ll initially haven’t any glasses or cups in your desk. In consequence, your waiter will know that you have not been served something in any respect so that they’ll know to go over and hand you a menu, introduce themselves and see whether or not they can take any orders. As soon as you’ve got been served you might need some empty glasses in your desk. The waiter will now know to ask to refill or take a special order.
This can be a demonstration of how no worth (no glass on the desk) and an empty worth (empty glasses on the desk) can have vital variations in that means they usually cannot at all times be used interchangeably.
In Swift, we categorical the flexibility of a property having no worth quite than a default worth by defining an optionally available Consumer
object:
var theUser: Consumer?
The ?
after our Consumer
tells the compiler that var theUser
will both include a worth of sort Consumer
or it is going to maintain nothing in any respect (we name this nil
).
It is good to know that the ?
is a extra handy to put in writing the next:
var theUser: Optionally available
Whereas the 2 methods of defining theUser
do the identical factor, it is best observe to put in writing var theUser: Consumer?
. It is simpler to learn and sooner to put in writing.
Observe that every one sorts in Swift could be written as an optionally available. For instance, in case you’re defining a String
which may must be initialized as “no worth” you may write: var theString: String?
.
The principle distinction between “no worth” and “default worth” is usually whether or not there’s any semantic that means to pointing at nothing or pointing to a default worth. For instance, an optionally available Bool
(Bool?
) virtually by no means is sensible; in most eventualities it is possible for you to to select a wise default worth that is protected to make use of. In different instances, one thing being empty or lacking might point out that enter from the person is required, or that you want to fetch knowledge from an exterior supply and it isn’t potential or cheap to offer a default worth.
Now that you know the way to put in writing optionally available properties, let’s have a look at how optionals are utilized in Swift.
Utilizing optionals in your code
As soon as you’ve got outlined an optionally available worth in Swift, it is vital that we deal with the potential of a worth being nil
in addition to the worth being non-nil
. Swift is fairly strict about this so optionals aren’t utilized in the identical approach as you’d use regular variables or constants.
For instance, if we contemplate the theUser
variable from earlier, we will not learn the title from this property like this:
var theUser: Consumer?
// Worth of optionally available sort 'Consumer?' should be unwrapped to consult with member 'title' of wrapped base sort 'Consumer'
print(theUser.title)
The Swift compiler will inform us that we have to “unwrap” worth of optionally available sort Consumer?
with the intention to entry its member title
. That is the compiler’s approach of telling us that theUser
might or will not be nil
so we have to deal with each eventualities.
Let’s check out severals methods by which we will “unwrap” our optionally available.
Unwrapping with if let
If we’re writing code the place we need to solely execute part of our script or operate in case the worth is not nil
, we will use one thing known as an if let
unwrap. This is what that appears like:
var theUser: Consumer?
// some place else within the code...
if let userValue = theUser {
print(userValue.title)
} else {
print("the person is nil")
}
This if let
makes an attempt to learn theUser
and we assign it to a continuing. This fixed is then made accessible within the if’s physique the place we all know that userValue
is of sort Consumer
. Exterior of our if physique we cannot be capable to entry userValue
; it is solely made accessible within the if. As wanted, we will present an else
to deal with eventualities the place theUser
is nil
.
Observe that the code above may very well be simplified a bit. Swift permits us to make use of one thing known as a shadow variable (variable of the identical title) for theUser
which might change the if let
as follows:
var theUser: Consumer?
// some place else within the code...
if let theUser {
print(theUser.title)
} else {
print("the person is nil")
}
Observe that theUser
within the if physique is just not the identical variable as theUser
outdoors of the if physique; it is a completely different property with the identical title. For that purpose, theUser
within the if physique is of sort Consumer
and out of doors of the if physique it is Consumer?
. This function of Swift is good whenever you’re accustomed to optionals however I discover that typically it is higher to offer a special title in order that it is clear whenever you’re utilizing your unwrapped property or whenever you’re utilizing your optionally available property.
Unwrapping optionals with guard let
Whereas if let
is nice for utilization within code the place it would not matter that a lot whether or not a worth is or is not nil
, you typically need to be sure that a worth is not nil
initially of a operate. With if let
this could usually imply that you just write an if let
initially of your operate after which write the entire operate physique within your if let
:
func performWork() {
if let unwrappedUser = theUser {
// do the work
}
}
This works however it may well result in loads of nested code. For eventualities the place you solely want to proceed in your operate if a worth is just not nil
, you need to use guard let
as a substitute:
func performWork() {
guard let unwrappedUser = theUser else {
return
}
// do the work
// unwrappedUser is obtainable to all code that comes after the guard
}
A guard
permits us to make sure that our person has a worth and that the unwrapped worth is obtainable to all code that comes after the guard
. After we’re utilizing a guard
we should present an else
clause that exits the present scope. Often which means we put a return
there with the intention to bail out of the operate early.
Unwrapping a number of properties
Each if let
and guard let
permit us to unwrap a number of properties directly. That is executed utilizing a comma separated checklist:
if let unwrappedUser = theUser, let file = getFile() {
// we now have entry to `unwrappedUser` and `file`
}
The syntax for guard let
is identical however requires the else
:
guard let unwrappedUser = theUser, let file = getFile() else {
return
}
// we now have entry to `unwrappedUser` and `file`
Observe that writing your code like this may require all unwraps to succeed. If both our person or file can be nil
within the instance above, the if physique would not be executed and our guard
would enter its else
situation.
Studying by way of optionally available chaining
If you’re working with an optionally available and also you’d prefer to get entry to a property that is outlined in your object, you may write an if let
after which entry the property you are thinking about. You noticed this earlier with Consumer
and its title
property:
if let theUser {
print(theUser.title)
}
If we all know that we’re solely within the title
property we will use a method known as optionally available chaining to right away entry the title
property and assign that to the property we’re writing the if let
for as a substitute.
This is what that appears like
if let userName = theUser?.title {
print(userName)
}
That is very handy once we’re in a scenario the place we actually solely care a couple of single property. If both theUser
is nil
or (if title
is optionally available) title
is nil
the if physique will not be executed.
We are able to use this method to entry bigger chains of optionals, for instance:
if let division = theUser?.division?.title {
}
Each theUser
and division
are optionals and we will write a sequence of entry utilizing ?
after every optionally available property. As soon as any of the properties within the chain is discovered to be nil
the chain ends and the result’s nil
.
For instance, if we simply assign the chain from above to a property that property is a String?
// division is String?
let division = theUser?.division?.title
The title
on the division property would not should be a String?
however as a result of we’re utilizing optionally available chaining we’ll get a nil
worth if both theUser
or division
is nil
.
This leads me to at least one final methodology that I would advocate for working with and that is utilizing the nil coalescing operator.
Unwrapping optionals utilizing nil coalescing
For any optionally available in Swift, we will present a default worth inline of the place we entry it. For instance:
let username: String?
let displayName = username ?? ""
The ??
operator within the instance above known as the nil coalescing operator and we will use it to offer a default worth that is utilized in case the worth we’re making an attempt to entry is nil
.
That is notably helpful when you want to present values to render in a person interface for instance.
It’s also possible to use this method together with optionally available chaining:
// division is String
let division = theUser?.division?.title ?? "No division"
Now, let’s check out one final methodology to unwrapping that I am solely together with for completeness; this strategy ought to solely be used as a final resort for my part.
Drive unwrapping optionals
For those who’re 100% completely certain that an optionally available worth that you just’re about to entry can by no means be nil
, you may pressure unwrap the optionally available when accessing it:
print(theUser!.title)
By writing an !
after my optionally available variable I am telling the compiler to deal with that property as non-optional. Which means I can simply work together with the property with out writing an if let
, guard let
, with out optionally available chaining or with out utilizing nil coaslescing. The most important draw back right here is that if my assumptions are mistaken and the worth is nil
in any case my program will crash.
For that purpose it is virtually at all times most popular to make use of one of many 4 protected approaches to unwrapping your optionals as a substitute.