Optional Type and Unwrapping Optionals In Swift

Swift optionals can be a bit confusing, in this article we’ll go into detail about optionals. We will look at how they can be used in code.

What is Optional?

Optional in Swift is a constant or variable that holds any value (int, float, string etc.) or does not hold any value (nil).

To specify an optional variable, one (?) must be added next to its type and must be written adjacent to the type. There must be no spaces.

// Optional
var username:String?

In the above, we have an optional variable because it doesn’t hold any value. It’s empty (nil). We can see keeping value with an if-else statement.

var username:String?

if username == nil
{
    print("it doesn't hold anything.")
}
else
{
    print("Yes, we found something in there.")
}

// Output: it doesn't hold anything

When it’s started our code printed “it doesn’t hold anything” on screen. Now let’s define something to the username and start the program again.

var username:String? = "Hello"

When we run the program again with this variable. We can see “Yes, we found something in there.” text on the screen.

In short, we use optionals to prevent the program from crashing when there is no data (zero), or when we want to work with a nil values.

Unwrapping Term

Before looking at the unwrap term, let’s write an optional variable with the help of the print function.

var username:String? = "Hello"

print(username)

// Output: Optional("Hello")

You must have noticed that you did not get the result you wanted, the text was not printed directly, first you saw a few error messages and then Optional(“Hello”).

This is because you cannot directly use an optional variable. Remember what I said at the beginning? Optional can be empty or full.

You need to open (unwrap) the option to find out whether it is empty or full. We have to unwrap the option to see the content of optional just like a box.

Unless the optionals are opened (unwrapped), it is unclear whether the value inside is empty or full.

First Technique: Forced Unwrap

When you are sure that a variable can no longer be empty, you can force unwrap this optional. One of the easiest ways to use value.

var username:String? = "Hello"
print(username!)

// Output: Hello

Now, the data held by the username variable is printed on the screen. The Int() function returns optional, so we can force unwrap and get the value in it.

var usernameID:String = "123123"
var ID:Int = Int(usernameID)!

// Output: 123123

A little footnote: In force unwrapping, unfortunately, the application will crash if the boxes you open are empty. Therefore, they are unsafe.

But if you are sure of everything and it must be opened, you can use it because it is simple to use in some situations.

little more information, you can force unwrap and examine exactly where your application crashed. It can help with debugging.

Second Method: Optional Binding

All right, but in some cases, you might think you need a safer route. For example, I have an application that uses a network what if the network connection is lost?

There is a safer method for such cases, which is Optional Binding, which is the topic we are currently processing.

let password:String? = "whatever123"

if let pass = password
{
    print(pass)
}

// Output: whatever123

The above code basically works like this, if there is a value in the password, the transfer takes place and the value in it is printed.

If you don’t want to use temporary variable you can replace it with bool test.

nil values cannot be passed, so false is returned, and “if” does not work. You can use else statement for different situations.

let password:String? = nil

if let pass = password
{
    print(pass)
}
else
{
    print("empty")
}

// Output: empty

Third Method: Nil Coalescing Operator

Another way to unwrap it safely is to use the zero-joining operator. This operator allows us to specify what happens when it is empty or full.

“??” add the operator next to the optional variable. It allows you to specify which value to return (default value) if no value is found.

let password:String? = nil
let pass:String = password ?? "Empty"

print(pass)

// Output: Empty

As you can see, empty is printed on the screen, if there was a value in it, we would see that value.

Fourth Method: Guard Statement

You can unwrap optionals using the guard statement. Again, it’s a safe choice and easy to use.

let backup:String? = nil

func checkBackUp(){
    guard let _ = backup else{
        print("No Backup Here")
        return
    }
}

checkBackUp()

// Output: No Backup Here

We created a function that tests whether a backup has been made. This is how guard unwrapping works.

Leave a Reply

Your email address will not be published. Required fields are marked *