in , ,

Swift Optionals

Swift Optionals
Swift Optionals

Swift Optionals: In this tutorial, you will learn about swift optionals, its use cases and optional handling in Swift.

In the previous tutorial, we learned about different data types accessible in Swift and furthermore noticed variable or consistent proclaimed of those types contains a default value.

In Swift optionals are nil or have a value. Before you can use an optional, you’ll need to unwrap it. Optionals are a powerful element of the Swift programming language since they make your code more safer and more beneficial. What’s more, as an iOS developer, it’s significant you know how to use optionals.

Example:

let someValue = Int()
print(someValue)

At the point when you run the program, the output will be:

0

Anyway there is another data type in Swift called Optional, whose default value is a null value (nil). You can use optional when you need a variable or consistent contains no value in it. An optional sort may contain a worth or missing a worth (a null value).

Non actually, you can think of optional as a shoe box. The shoe box might possibly contain a shoe in it. In this way, you should know in advance while getting to the shoe from the box.


How to declare an Optional?

You can essentially address a Data type as Optional by appending! or then again? to the Type. In the event that an optional contains a value in it, it returns the value as Optional<Value>, if not it returns nil.

Example 1: How to declare an optional in Swift?

var someValue:Int?
var someAnotherValue:Int!
print(someValue)
print(someAnotherValue)

At the point when you run the program, the output will be:

nil
nil

In the above program, we have instated an optional sort using? furthermore, !. The two different ways are legitimate to create an optional however there is one significant difference which we will investigate underneath.

Declaring an optional Int means the variable will either have an integer value or no value. Since no value is assigned to the variable, you can see both print statement outputs nil on the screen.


Example 2: Assigning and accessing a value from an optional

let someValue:Int? = 5
print(someValue)
print(someValue!)

At the point when you run the program, the output will be:

Optional(5)
5

In the above program, we have declared an optional of Int type and assigned value 5 in it.

As should be obvious, printing the optional as print(someValue) doesn’t give you 5 however Optional(5). It is of the structure as described above: Optional<value>. In order to access the value from it, we need a mechanism called unwrapping.

You can open up an optional by affixing! character toward the finish of the variable/constant as in the next line print(someValue!). print(someValue!) opens up the optional and outputs 5 on the screen.

Notwithstanding, recollect, this sort of opening up system should possibly be used when you are sure that the optional will sure have a value when you access it.


Example 3: Explicitly declaring an unwrapped optional

You can likewise create an unwrapped optional as:

let someValue:Int! = 5
print(someValue)

At the point when you run the program, the output will be:

5

In the above program, Int! creates an unwrapped optional, which consequently opens up the worthwhile you access it so you don’t have to every time append the ! character.

Be sure while you use these sorts of optionals, the variable will consistently have to have a value when you access it. On the off chance that you don’t, you will get a fatal error crash.


Example 4: Fatal error when accessing a null unwrapped optional

var someValue:Int!
var unwrappedValue:Int = someValue //crashes due to this line

At the point when you run the program, you will get a crash as fatal error: unexpectedly found nil while unwrapping an Optional value because that the code unwrappedValue:Int = someValue attempts to assign value from Optional someValue to variable unwrappedValue.

Notwithstanding, somevalue is an Optional type that contains nil value. Attempting to assign nil value to variable unwrappedValue which is not optional will lead to crash.

There are various strategies to deal with this case which are clarified beneath.


Optional Handling

To use the value of an optional, it should be opened up. Better approach to use optional value is by conditional unwrapping instead of force opening up using ! operator.

This is on the grounds that conditionally unwrapping inquires as to whether this variable has a value? . On the off chance that yes, give the worth, else it will deal with the nil case.

Despite what might be expected, force opening up says This variable has a worth while you use it. Consequently, when you force unwrap a variable that is nil, your program will throw a startlingly discovered nil while unwrapping an optional exemption and crash. A portion of the procedures for contingent unwrapping are clarified beneath:

1. If-statement

You can use if statement and compare optional with nil to see if an optional contains a value or not. You can use the comparison operator “equivalent to” operator (==) or the “not equivalent to” operator (!=) in the if statement.

Example 5: Optional handling with if else statement

var someValue:Int?
var someAnotherValue:Int! = 0
        
if someValue != nil {
	print("It has some value \(someValue!)")
} else {
	print("doesn't contain value")
}
        
if someAnotherValue != nil {
	print("It has some value \(someAnotherValue!)")
} else {
	print("doesn't contain value")
}

At the point when you run the program, the output will be:

doesn't contain value
It has some value 0

In the above program, the code inside if statement executes if an optional contains a worth, in any case, the statement inside the else block executes. The significant drawback of optional dealing with using this strategy is, you actually need to unwrap the value from optional using ! operator.


2. Optional Binding (if-let)

Optional binding assists you with seeing if an optional contains a value or not. On the off chance that an optional contains a value, that worth is accessible as a temporary constant or variable. In this manner, optional binding can be used with an if statement to check for a value inside an optional, and to extract that value into a constant or variable in a single activity.

Example 5: Optional handling using if let statement

var someValue:Int?
var someAnotherValue:Int! = 0
       
if let temp = someValue {
	print("It has some value \(temp)") 
} else {
	print("doesn't contain value")
}
        
if let temp = someAnotherValue {
	print("It has some value \(temp)")
} else {
	print("doesn't contain value")      
}

At the point when you run the program, the output will be:

doesn't contain value
It has some value 0

In the above program, the code inside if statement executes if the optional contains a value. In any case, the else block gets executed. The if-let statement likewise consequently unwraps the value and spots the unwraps value in temp constant. This procedure has significant benefit since you don’t have to forcely unwraps the value although being sure an optional contains a value.


3. Guard statement

You can use the guard to deal with optional in Swift. Try not to stress in the event that you don’t have an idea what guard is. For the present, simply consider guard is an if-else condition with no if block. In the event that the condition fails, else statement is executed. If not, the next statement is executed

Example 6: Optional handling using guard-let

func testFunction() {
	let someValue:Int? = 5
	guard let temp = someValue else {
		return
	}
	print("It has some value \(temp)")
}

testFunction()

At the point when you run the program, the output will be:

It has some value 5

In the above program, the guard contains a condition if an optional someValue contains a value or not. Assuming it contains a value, the guard-let statement consequently unwraps the value and spots the unwrapped value in temp constant. Something else, else block gets executed and it would get back to the function. Since the optional contains a value, the print function is called.


4. Nil-coalescing operator

In Swift, you can likewise use a nil-coalescing operator to check if an optional contains a value. It is characterized as (a ?? b). It unwraps and optional a and returns it on the off chance that it contains a value, or returns a default value b if an is nil.

Example 7: Optional handling using nil-coalescing operator

var someValue:Int!
let defaultValue = 5
let unwrappedValue:Int = someValue ?? defaultValue
print(unwrappedValue)

At the point when you run the program, the output will be:

5

In the above program, variable someValue is characterized as optional and contains nil value. The nil coalescing operator fails to unwrap the optional hence brings defaultValue back. Hence the statement print(unwrappedValue) outputs 5 in the console.

var someValue:Int? = 10
let defaultValue = 5
let unwrappedValue:Int = someValue ?? defaultValue
print(unwrappedValue)

At the point when you run the program, the output will be:

10

Nonetheless, in the above program, the optional variable someValue is instated with value10. Along these lines, the nil coalescing operator successfully unwraps the value from someValue. Subsequently, the statement someValue ?? defaultValue returns 10 and the statement print(unwrappedValue) outputs 10 in the console.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

HTML Styles

HTML Styles

HTML Text Formatting

HTML Text Formatting