Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

optionals
swift
data types
communitycreator

What are optionals in Swift?

Cynthia Ezeh

As you begin to write code, you may discover that your code will sometimes run successfully and sometimes fail. One of the most prevalent causes of code failure is when it tries to use faulty or missing data. However, since Swift is a very safe language, it ensures that your codes will not fail in unexpected ways. Swift did this by introducing optionals.

What is an optional in Swift?

With an optional, there are two possibilities: either there is a value, which you may obtain by unwrapping the optional, or there isn’t one at all. An optional serves as a container for a specific type of value. This container may or may not contain a value.

How to declare an optional

A question mark ? is used to declare an optional. An optional variable is declared by appending a question mark to the end of the variable’s data-type declaration. For instance:

var name: String?

When should an optional be used?

Use an optional when you want to be on the safe side. Declare the variable as an optional type if you are unsure whether or not it will have a value.

It is safer to declare this kind of variable as an optional to avoid surprises when coding.

Unwrapping optionals

An optional wraps a value up like a parcel, meaning that you cannot access the value of an optional like you access the value of a variable or constant. So, you would need to unwrap an optional value in order to use it.

You can perform unwrapping in the following ways:

  • Using an if-else block
  • Using a nil coalescing operator
  • Using forced unwrapping
  • Using optional chaining
  • Using optional binding

In this shot, we’ll concentrate on the first three because they’re the most common.

Optional unwrapping using an if-else block

Unwrapping is the process of checking the variable to ensure that the optional value is not nil. You can accomplish this with a simple if-else block (if, if let or guard let), like this:

var name: String? //optional declaration

if name != nil{
 print("Name is Not nil")
}
else{
 print("Nil")
}//Output : Nil

// The if let optional unwrapping
if let somethingToUnwrap = name {
    print("\(somethingToUnwrap.count) letters in total")
} else {
    print("Name is missing.")
}

// The guard let optional unwrapping
func greet(_ name: String?) {
    guard let somethingToUnwrap = name else {
        print("Name is missing!")
        return
    }
    print("Hello there, \(somethingToUnwrap)!")
}

Optional unwrapping using the nil coalescing operator

The nil coalescing operator functions as a shorthand representation for the conventional if-else block.

If there is a value inside an optional, the nil coalescing operator unwraps it and returns it. If the optional was nil, and there was no value, a default value is used instead. In either case, the result will not be optional. Instead, it will either return the value from within the optional or the default value used as a backup.

var variableName: String?
var message = variableName ?? "Default value"
print(message) // Default value

variableName = "This is a string"
message = variableName ?? "Default String"
print(message) // This is a string

Optional unwrapping using forced unwrapping

Here, unwrapping is a bit different because you’re accessing an optional regardless of its value (nil or not nil), and forced unwrapping is quite contradictory. If a nil optional is unwrapped, an error message stating “Unexpectedly found nil while unwrapping an optional value.” is thrown, and your program will terminate or crash.

You should only use forced unwrapping in a pre-defined environment where you know the optional value will not be nil. By using the exclamatory ! operator, you can forcefully unwrap an optional, as shown below:

var country: String?;
print(country!) // Unexpectedly found nil while unwrapping an Optional value

Wrapping up

Note that using forced unwrapping when you are not sure an optional contains a value can cause your code to fail. So, ensure that you have a value before using an exclamation mark to force unwrap an optional.

There you have it! Feel free to use optionals in your codes. Thanks for reading!

RELATED TAGS

optionals
swift
data types
communitycreator
RELATED COURSES

View all Courses

Keep Exploring