Let’s understand what is optional in Swift and how to use !!

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

The example below shows how to declare optional variables.

    1.    var optionalVariable1: String?
    2.    var optionalVariable2: Int?
    3.    func swapInt(int1: Int?, int2: Int?) // as a function argument
    4.    func doSomething() -> String? // function return value as optional

So basically you use optional when you think some variable’s value or function’s return value can be nil in some conditions.
You can check the optional variable against nil before accessing, like below

If optionalVariable1 != nil {
     // your code
}

The example below uses the initializer to try to convert a String into an Int:

    1.    let possibleNumber = "123"
    2.    let convertedNumber = Int(possibleNumber)
    3.    // convertedNumber is inferred to be of type "Int?", or "optional Int"

Because the initializer might fail, it returns an optional Int, rather than an Int. An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all. (It can’t contain anything else, such as a Bool value or a String value. It’s either an Int, or it’s nothing at all.)

NOTE:
You can’t use nil with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.

How to use optional

Before using the optional value you must unwrap the optional. Below are the ways we can unwrap an optional.

    1.    If statement and Force Unwrapping
    2.    Optional Binding
    3.    Implicitly Unwrapped Optionals

Unwrapping in Swift means getting the value of the variable. To unwrap the value we use exclamation mark (!) to the end of the optional’s name.

    •    If statement and Force Unwrapping:

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).

If an optional has a value, it’s considered to be “not equal to” nil:
    1.    if convertedNumber != nil {
    2.       print("convertedNumber contains some integer value.")
    3.    }
    4.    // Prints "convertedNumber contains some integer value."

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:

    1.    if convertedNumber != nil {
    2.       print("convertedNumber has an integer value of \(convertedNumber!).")
    3.    }
    4.    // Prints "convertedNumber has an integer value of 123."

NOTE:
Trying to use ! to access a nonexistent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

    •    Optional Binding

You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.

Write an optional binding for an if statement as follows:
    1.    if let constantName = someOptional {
    2.        //statements
    3.    }

You can write the possibleNumber example one mentioned above to use in optional binding way.

    1.    if let actualNumber = Int(possibleNumber) {
    2.       print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
    3.    } else {
    4.       print("The string \"\(possibleNumber)\" could not be converted to an integer")
    5.    }
    6.    // Prints "The string "123" has an integer value of 123"

In this code in line1 if(Int(possibleNumber)) return a value it will assign in the variable actualNumber and if part(line2) will executed , if the return value is nil
then else part will execute and line4 will print.

You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. The following if statements are equivalent:

    1.    if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    2.       print("\(firstNumber) < \(secondNumber) < 100")
    3.    }
    4.    // Prints "4 < 42 < 100"

NOTE:
Constants and variables created with optional binding in an if statement are available only within the body of the if statement.


    •    Implicitly Unwrapped Optionals

As described above, to use optional value you need to unwrap it first, but every time unwrapping using optional binding might be annoying.

Sometimes it’s clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it’s useful to remove the need to check and unwrap the optional’s value every time it’s accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. See the below example.

    1.    var optionalVariable1: String! // no ‘?’ mark
    2.    var optionalVariable2: Int! // no ‘?’ mark

But in this case you must be confirmed that before using the variable it should have some value assigned. This type of variable we basically use for outlets, and properties which holds data from other class. Usage as given below.

    1.    let optionalVariable1: String! = "An implicitly unwrapped optional string."
    2.    let implicitString: String = optionalVariable1 // no need for an exclamation mark (!)

NOTE:
If an implicitly unwrapped optional is nil and you try to access its wrapped value, you’ll trigger a runtime error. The result is exactly the same as if you place an exclamation mark after a normal optional that doesn’t contain a value.


You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:

    1.    if optionalVariable1 != nil {
    2.       print(optionalVariable1!)
    3.    }
    4.    // Prints "An implicitly unwrapped optional string."

Hope this article will help you guys. If you have any doubt, suggestions please do comment.

Comments

  1. Nice Article, There is an update in swift for ImplicitlyUnwrappedOptional that has been abolish in latest version of Swift 4.1 onwards. So in that case if you print ImplicitlyUnwrapped value, then the value of that will print as optional value.

    ReplyDelete

Post a Comment

Popular posts from this blog

AutoFill OTP in iOS12 new feature (iOS12).

What is method chaining ?