Optionals in Swift ( ! ? )

What Is an Optional

Optionals in Swift , The underlying concept of an optional is easy to grasp. An optional acts as a container for a value of a particular type. The container holds a value or it doesn’t. Type safety is a cornerstone of the Swift language. As a result, variables and constants need to be initialized before they can be accessed.

Swift is a very safe language, by which I mean it works hard to ensure your code never fails in surprising ways. One of the most common ways that code fails is when it tries to use data that is bad or missing

A regular variable must contain a value. Example: String must contain a string, even if that string is empty, i.e. “”. It cannot be nil.
An optional variable might contain a value, or might not. It must be unwrapped before it is used. Example: String? might contain a string, or it might contain nil. The only way to find out is to unwrap it.

An implicitly unwrapped optional might contain a value, or might not. But it does not need to be unwrapped before it is used. Swift won’t check for you, so you need to be extra careful. Example: String! might contain a string, or it might contain nil – and it’s down to you to use it appropriately. It’s like a regular optional, but Swift lets you access the value directly without the unwrapping safety. If you try to do it, it means you know there’s a value there – but if you’re wrong your app will crash.

Declaring Optionals

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

Here’s an optional Integer declaration −

var mycodetipsInt: Int?

Here’s an optional String declaration −

var mycodetipsStr: String?

Declaration is equivalent to explicitly initializing it to nil which means no value −

var mycodetipsStr: String? = nil

var mycodetipsString:String? = nil

if mycodetipsString != nil {
   print(mycodetipsString)
} else {
   print("This String has nil value")
}

Output : This String has nil value

Forced Unwrapping

Optionals in Swift lets you override its safety by using the exclamation mark character: !. If you know that an optional definitely has a value, you can force unwrap it by placing this exclamation mark after it. If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. Putting an exclamation mark at the end of the variable.

var mycodetipsString:String?

mycodetipsString = "Hello, Swift !"

if mycodetipsString != nil {
   print( mycodetipsString! )
} else {
   print("mycodetipsString has nil value")
}

Outout : Hello, Swift !

if you try this on a variable that does not have a value, your code will crash.

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

Automatic Unwrapping

You can declare optional variables using an exclamation mark instead of a question mark. Such optional variables will unwrap automatically and you do not need to use any further exclamation mark at the end of the variable to get the assigned value.

var mycodetipsString:String!

mycodetipsString = "Hello, Swift !"

if mycodetipsString != nil {
   print(mycodetipsString)
} else {
   print("mycodetipsString has nil value")
}

Unwrapping Optionals

Because the value of an optional is wrapped in a container, you cannot access the value of an optional like you access the value of a variable or constant.

let mycodetipsbody: String = message

The above statement will generate an error. Xcode’s suggestion a try by adding an exclamation mark after the name of the optional.
But what happens if the optional has no value?

var message: String?
let mycodetipsbody: String = message!

When the optional message doesn’t contain a value, an error is thrown. 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.

If you force unwraps an optional that doesn’t contain a value, your process or application terminates. Optional should never be forced unwrapped unless you are absolutely certain it contains a value.

Optional Binding

Let’s add some safety to the example. Before we assign the value of the message to the body, it is better to first check if the optional contains a value.

var message: String?

if message != nil {
    print(message!)
} else {
    print("no value found")
}

This is much safer and we avoid the error we encountered earlier. The downside is that the solution is verbose. A more common approach is to use optional binding to safely unwrap the value of the optional.

var message: String?

if let unwrappedMessage = message {
    print(unwrappedMessage)
} else {
    print("no value found")
}

Optionals in Swift inspects the value of the message and assigns the value to the unwrappedMessage constant only if the message contains a value. The unwrappedMessage constant is then available in the if clause. If the message doesn’t contain a value, the else clause is executed. The solution is still verbose, but it is easy to read and understand. Optional binding is very powerful.

var name: String? = "mycodetips"
var high: Float? = 127.00
var low: Float? = 99.23

if let name = name, let high = high, let low = low {
    print("\(name): \(high) - \(low)")
}

Happy Swift Coding 🙂


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top