Swift optionals are fundamental part of programming. At first, they seem a bit confusing. However, the more you dig into them, the more you realize that there’s a lot to master about them.
In this title, I will give you full details about options in Swift. Besides, we also give you the complete guide to making your code more secure. Ready? Let’s get started
What Are Swift Optionals?
Swift optionals represent something that has no value. For example, consider this code:
What value should position have when that code runs?
- It can’t hold 0 because that’s the position of Margaret.
- t could hold -1 as a magic number because that’s easy to remember but an impossible number
None of them are good solutions. This is where options come in, they represent no value. An empty optional integer is not zero, -1, 16777216 or any other number. It’s nothing.
Swift optionals are best thought of as boxes that may or may not contain a value.
When are optionals useful?
Swift optionals let us represent missing, unknown, or deleted data. If you have a User struct with an age of 0, that might mean they have just been born or it might mean you don’t know – it’s hard to tell. By having made that same value optional it becomes clearer: when it’s 0 it’s a newborn baby, and when it’s nil you just don’t know the age.
How To Use Swift Optionals
You now know that you use optionals in scenarios where a value may be absent. The rule is: An optional either has a value or is nil. For example:
Here’s what happens in the above example:
- On the first line, you’re creating a constant name of type String?.
- The question mark ? written right after the type annotation, indicates that this constant is optional.
- You assign nil to name, so this constant does not have a value. It’s nil. We say that name “is an optional”.
What is unwrapping?
Because the options may or may not be empty, Swift won’t let you freely use them. If an option is empty – no then it cannot be used in your code. For example: If you have an optional string, you don’t want to try and show it to your users – the string might be empty.
To keep you from using nil values by accident, Swift makes us unwrap the optionals: the process of looking inside to see whether there is a value there or not. If there is a value then Swift will unwrap it and send it back to us as a non-optional, but if there isn’t then the test will fail. For example:
The other common way to unwrap optionals is using guard let syntax, which is similar to if let except:
- If a guard unwraps fails you must exit the current scope. This means existing your method, but it might also mean exiting a condition or loop. Swift will refuse to compile unless you do this.
- If a guard unwraps succeeds, the unwrapped value exists after the guard block finishes. This is the opposite of if let, where the unwrapped value only exists inside the first code block.
What are optional optionals?
Optional optionals are a good sign that you need to rethink your code a little. If an optional integer is like a box that might have a number or might not, then an optional optional integer is that box inside another box.
Optional optionals are written with two question marks, like this: Int?? or String??. You can even make optional optionals, but honestly, anything beyond a regular optional is a bad idea.
How can you check a Swift optional is empty?
The simplest way of checking for empty optionals is to compare them against nil, like this:
In switch blocks you can also use question marks to check for the presence of a value, while also unwrapping whatever was found. For example:
The same question mark syntax also works with arrays. If you use for case let someValue? in someArray then Swift will check each optional, ignore any that are nil, but unwrap any that aren’t nil and execute your loop body for that item.
In Swift, how are optionals implemented?
Under the hood, optionals are actually Swift enums that have two cases:
- .none for empty optional
- .some if they do have a value.
Although there is some special compiler work around things like if let and guard let, a lot of the functionality of optionals themselves is actually implemented in Swift code – you can read the source code right here. It’s not very long, and I think you’ll learn a lot! Here’s how optionals are define.
What protocols do Swift optionals conform to?
You just saw how optionals were defined, and there’s conformance right there for ExpressibleByNilLiteral so that we can make optionals that have an initial value of nil. However, optionals also use conditional conformance to conform to both Equatable and Hashable but only if the type they contain conform to those protocols.
So, you can write code like this:
This functionality automatically enabled through conditional conformances. So, if you want to use it with your custom types make sure your type conforms to Equatable or Hashable.
In Swift, optionals are one of the most important safety features. It makes sure we never try to work with empty memory by accident. In fact, through the above reading, we hope that it is useful for you. In particular, during the process of running Swift, in case you’re facing any difficulty, you should ask ArrowHiTech for help. We believe with 13+ years in the technology area as well as Swift and Mobile Development Services, we can help you solve everything about Swift.