Table of contents
1.
Introduction
2.
Declaration of Optionals
3.
Unwrapping Optional Variables in Swift
3.1.
Using If-else block 
3.2.
Forced Unwrapping
3.3.
Optional Binding
3.4.
Unconditional Unwrapping
3.5.
Using Nil-Coalescing
4.
Frequently Asked Questions
4.1.
What is the use of the let keyword in swift?
4.2.
How do we get the value of the optional variable through 1st method?
4.3.
What is the nil-coalescing operator?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Optionals in Swift

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will be learning about the optionals in swift. If you come from other object-oriented languages, then you hardly have any idea about the optionals that exist in swift. Optionals are "used when a value may be missing. An optional can represent one of two things: either there is a value, and you can access it by unwrapping the optional, or there isn't a value at all". We can perform any action on the optionals if it is not null.

Declaration of Optionals

Optionals are also declared just like the regular variables with an additional question mark symbol (?).

Syntax:

<data-item> <var-name>:<data-type>?

Example: Simple example of optionals.

Code:

// Declaring an optional.
var str:String? = nil

str = "Welcome to Coding Ninjas!"
print(str)


Output:

Optional("Welcome to Coding Ninjas!")

Explanation: Don’t worry if you are getting an error warning along with this output. It simply tells us to unwrap the optional variable to get the actual value of the variable. So, now let’s learn how to unwrap the optional variables.

Unwrapping Optional Variables in Swift

We cannot use the values of optional variables for any operation until that variable is cast to its primitive or user-defined data type. This procedure of conversion is known as unwrapping. We can also consider that “Unwrapping in Swift is just a check to see if the Optional value is nil or not, and if it isn't, it performs a task”. There are five ways to unwrap a variable in swift.

Using If-else block 

Considering the second definition mentioned above, we can check this using the if-else block.

Example: Using if-else to check whether the variable is nil or not.

Code: 

// Declaring an optional.
var str:String? = nil

str = "Welcome to Coding Ninjas!"

// Checking using if-else statement.
if(str != nil){
    print("Variable is not nil")
}
else{
    print("Variable is nil")
}


Output:

Variable is not nil

Forced Unwrapping

As the name suggests here, we are forcefully checking the value of the optional variable without knowing whether it is nil or not. Forced unwrapping should only be used in a pre-defined scenario where you know the optional value won't be nil. If we try to unwrap a nil variable, it will show the error.

We unwrap the variable using the exclamatory (!) symbol.

Example: In this example, we will unwrap both nil and not nil variable.

Code: 

// Declaring an optional.
var str:String? = nil
// Unwrapping a nil variable.
//print(str!)
// Assigning value to the variable.
str = "Welcome to Coding Ninjas!"

print(str!)


Output:

Welcome to Coding Ninjas!

Explanation: If you run this program without commenting on the fourth line, you will get many errors on your console.

Optional Binding

Utilizing an if-else block is comparable to using optional binding. The sole difference is that if the optional value is not nil, the unwrapped value is allocated to a new constant, and operations on that constant are executed.

Here we use the if-let statement to use this technique.

Example: Using if-let statement for unwrapping.

Code:

// Declaring an optional.
var str:String?

str = "Welcome to Coding Ninjas!"

// Here we are using if-let statement.
if let varStr = str{
    // Print the new variable's value.
    print(varStr)
}


Output:

Welcome to Coding Ninjas!

Explanation: Here, we created a new variable, assigned the optional variable's value to the new variable, and then printed it on the console. If our optional variable is null, the if-let block will not be executed.

Unconditional Unwrapping

Instead of a question mark, you can use an exclamation mark to specify optional variables. Such optional variables will automatically unwrap, and you will not need to add another exclamation mark to the end of the variable to retrieve the allocated value.

Example: Demonstrating unconditional unwrapping.

Code:

let numVar = Int("348")!
print(numVar)


Output:

348

Using Nil-Coalescing

The if-else block is represented by the nil coalescing operator, a shorthand notation for the ordinary if-else block. When an optional value is unwrapped, and a nil value is detected, an additional default value is supplied and utilized instead.

Example: Using nil-coalescing to gey the value of an optional variable.

Code:

var str: String?

// If str is nil, then the other string is assigned.
var newStr = str ?? "Some Default String."

print(newStr)

str = "Welcome to Coding Ninjas."

// Here, str is not nil therefore, its value is assigned.
newStr = str ?? "Some Default String."

print(newStr)


Output:

Some Default String.
Welcome to Coding Ninjas.

Explanation: Here we are using the nil-coalescing technique to know whether the optional variable is nil.

Frequently Asked Questions

What is the use of the let keyword in swift?

To create immutable variables in Swift, we use the let keyword. A constant that can only be initialized once is called an immutable variable.

 

How do we get the value of the optional variable through 1st method?

Just by using the 1st method (if-else method), you cannot get the value of the optional variable because, in that method, we just find out whether the variable is nil or not. If you want to get the value of the variable, then you need to use forced unwrapping.  

 

What is the nil-coalescing operator?

In numerous programming languages, including C#, PowerShell as of version 7.0.0, Perl as of version 5.10, Swift, and PHP 7.0.0, the null coalescing operator is a binary operator, which is part of the syntax for a simple conditional expression.

Conclusion

In this article, we have extensively discussed the Optionals in swift. We discussed the optionals and how to unwrap them.

We hope that this blog has helped you enhance your knowledge regarding Optionals. Check out the awesome content on the Coding Ninjas Website, Swift Environment setupSwift setsSwift dictionarySwift Online ResourcesCoding Ninjas Studio ProblemsCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas CoursesCoding Ninjas Studio Contests, and Coding Ninjas Studio Test SeriesDo upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass