Optionals and Unwrapping in Swift

Talha Saygili
4 min readJan 9, 2023

--

Type safety is a cornerstone of the Swift language. When a variable is defined, its type is also defined, if not, Swift knows what type it is in the background and makes automatic identification. In this case, a variable will have one type and will throw an error when it tries to assign a different type. In addition to the basic data types String, Character, Int, Float, Double and Bool; Swift also has a different data type as Optional.

What is Optional?

An optional acts as a container for a value of a particular type. The container holds a value or it doesn’t.

If you fetch data from a remote backend, for example, you don’t know whether you are going to receive a valid response until the network request has completed. In such scenarios, you need the ability to represent a different state, the absence of a value. And that is where optionals come into play.

The optional type is also defined over the specific data type. Our purpose of making Optional is because there is a possibility that this variable is nil. So, when we define a variable of type Int Optional, there are two possibilities; Int value or nil. In String Optional, either String or nil.

Declaration

To declare an optional, we use a question mark. In the following example, we declare an optional of type Int? or optional Int. The question mark indicates that we are dealing with an optional.

// Standard Int Assignment

var someValue: Int = 15
print(someValue)
// 15
print(type(of: someValue))
// Int


// Optional Int Assignment

var optionalValue: Int?
print(optionalValue)
// nil
print(type(of: optionalValue))
// Optional<Int>

Unwrapping

You must unwrap the value of an Optional instance before you can use it in many contexts. Because Swift provides several ways to safely unwrap optional values, you can choose the one that helps you write clear, concise code.

1- Forced Unwrapped

By appending an exclamation mark at the end of an optional, the optional is forced unwrapped. This means that we unwrap the value of the optional’s container no matter what it contains. If the optional has a value, we can read the value. If the optional’s container is empty, an error is thrown.

Optionals should never be forced unwrapped unless you are absolutely certain it contains a value.

    var howMany: Int = optionalValue! // Forced Unwrapped with '!' sign

for _ in 0..<howMany{
print("Hello World!")
}

// Hello World!
// Hello World!
// Hello World!
// Hello World!
// Hello World!

2- Optional Handling

Conditionally unwrapping asks “Check if this variable has a value?” . If yes, give the value, otherwise it will handle the nil case.

a. If-Statement

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

    if optionalValue != nil{
var howMany: Int = optionalValue!

for _ in 0..<howMany{
print("Hello World!")
}
}else{
print("Optional Value is nil.")
}

// Hello World!
// Hello World!
// Hello World!
// Hello World!
// Hello World!

b. Optional Binding

Optional binding can be used with if statement to check for a value inside an optional, and to extract that value into a constant or variable in a single action.

    if let howMany = optionalValue{
for _ in 0..<howMany{
print("Hello World!")
}
}else{
print("Optinal Value is nil")
}

// Hello World!
// Hello World!
// Hello World!
// Hello World!
// Hello World!

c. Guard Statement

You can think of guard as an if-else condition with no if block. If the condition fails, else statement is executed. If not, next statement is executed.

    func testGuard(optionalValue: Int?){
guard let howMany = optionalValue else{
print("Optional Value is nil")
return
}
for _ in 0..<howMany{
print("Hello World!")
}
}

testGuard(optionalValue: optionalValue)
// Hello World!
// Hello World!
// Hello World!
// Hello World!
// Hello World!

var secondOptional: Int?
testGuard(optionalValue: secondOptional)
// Optional Value is nil

d. Nil-Coalescing Operator

Use the nil-coalescing operator (??) to supply a default value in case the Optional instance is nil

    let defaultLoop = 3
var howMany: Int = optionalValue ?? defaultLoop
for _ in 0..<howMany{
print("Hello World!")
}
// Hello World!
// Hello World!
// Hello World!
// Hello World!
// Hello World!

var secondOpt: Int?
var loopNumber: Int = secondOpt ?? defaultLoop
for _ in 0..<loopNumber{
print("Hello World!")
}
// Hello World!
// Hello World!
// Hello World!

--

--