Why learning about Swift Optionals is non-optional
- danielardelsmith
- Feb 25
- 5 min read

Have you ever had your app crash because of a missing value? Ever tried to use a variable that hasn't been initialised yet? In many languages, these errors can slip through unnoticed - especially when dealing with external data sources where data may not be loaded and ready yet. Swift has a built in safety net for cases like this - optionals. With optionals, Swift ensures that you never access an empty value without checking it first, saving you from dreaded runtime errors.
Let's imagine an analogy:
Think of yourself as a receptionist, and think of a variable to be a box like a mailbox containing an important document. You're told to open the box, take out the document, and use some data within the document to performa a task. However, the mail service hasn't delivered yet and the box is empty! You didn't expect this mailbox to be empty so, rationally, you freak out and go home. Now let's introduce optionals. Imagine the mailbox has a label attached to it that says, "might be empty!" and has a little notice next to it outlining some default data or method for you to use if you find nothing inside. This is what an optional does!
Okay, you've quit your job as a receptionist because you didn't like working around Schrödingers mailbox, and instead decide to write apps using Swift, where optionals make uncertainty more managable. Let's have a look at a simple example:
Show me an optional in action!
Say we're designing a simple social media app that displays a user's information, but it has to grab this information form a server. What if the user hassn't created a profile yet and wants to browse your app anonymously without an account? When initialising the variable containing a potenially missing value, we simple add a '?' to the data type. Have a look:
var username: String?
This syntax actually wraps a String inside our new data type, Optional, telling Swift that this variable may or may not contain a value. We can then attempt to populate the variable with some value:
username = getUsernameFromServer()
Now, when we access this variable, we are enforced by Swift to check its contents before using it. There's a few ways we can access it:
Checking its contents first
if let value = username {
print("Hello, \(value).")
}
else {
print("Hello, Anonymous.")
}
This is the most verbose way to check whether a value exists within a variable and allows us to handle both cases separately. We're asking Swift, "if there is a value inside 'username,' and you can place it in the variable 'value,' let us do something with 'value.' Otherwise, run the 'else' statement."
Coalescing to a default value
Instead of manually checking whether the contents of a variable is empty, and defining the code to run if it is, we can instead provide a default value for Swift use if the variable is found to be empty. this is called coalescing, and we can use the symbol '??' to do so:
let value = username ?? "Anonymous"
print("Hello, \(value).")
Here, we're telling Swift to use the string "Anonymous" if the value is empty. See how much cleaner that is compared to the verbose version? We can even emit the first line and place the coalescing directly in the print statement to make it even cleaner:
print("Hello, \(username ?? "Anonymous").")
Both methods of using optionals has its use case. For example, our app may not allow anonymous browsing, therefor we would use the first method to complete some entirely different action if the value is empty (maybe asking the user to create a profile). However, the second method is great for times where you're happy to provide a default value.
Force unwrapping optionals (careful!)
The third method for handling optional values is to force unwrap them. This allows us to skip checking their contents and skip providing a default value. However, you should only use this method if you can guarantee that the variable contains a real value, not 'nil,' otherwise your app will crash! To force unwrap an optional, we simply place a '!' symbol after the use of the variable. Take a look:
let value = username!
print("Hello, \(value).")
That's pretty much it! You've covered the basic use cases of declaring an optional variable, how to check its contents, how to coalesce its contents, and how to force Swift to unwrap and use it anyway. Remember, only force unwrap an optional variable if you can guarantee that a real value is inside!
Writing Functions That Might Return a Value
Earlier, we used a function called 'getUsernameFromServer().' The actual meat and potatoes of this function is outside of the scope of this guide. However, it's important to know how to write functions like this yourself, where a function performs some logic, then may or may not be able to return a real value. Just like when we declare an optional variable, we use a '?' in the function declaration to denote that it might return a real value. Let's have a look:
func getUsernameFromServer() -> String? {
// simulate a random chance of success
let success = Bool.random()
if success {
// simulate a successful server response
return "Daniel"
}
else {
// simulate a failed server response
return nil
}
}
We're not really writing a social media app that connects to an external data source. This function only simulates how the 'getUsernameFromServer()' function might act. Instead of using a random value, you'd actually implement logic to contact and retrieve data from a server, check its response, then return the response to the caller, or return 'nil' if no response was available.
Either way, notice the '?' in the function declaration where we specify the return type as 'String.' When you call this function, you are forced to either check its contents, coalesce it to a dafault value, or force unwrap it (you probably shouldn't). What's neat about Xcode is that it will notice you are using a function that returns an optional value, and will throw up a warning if you haven't handled the optional value correctly!
Found this guide useful? Share it with your Swift developer friends on social media!
Want to see more of my work? Check out the app I just released for the Apple Watch, FlexTracker - a simple shift tracking app for those with on or multiple employments that need an intuitive way to measure their work-life balance!
Have some questions or feedback? Connect with me here on LinkedIn.