Updated for Xcode 14.2
Swift’s optionals can either store a value, such as 5 or “Hello”, or they might be nothing at all. As you might imagine, trying to add two numbers together is only possible if the numbers are actually there, which is why Swift won’t let us try to use the values of optionals unless we unwrap them – unless we look inside the optional, check there’s actually a value there, then take the value out for us.
There are several ways of doing this in Swift, but one of the most common is if let
, like this:
func getUsername() -> String? {
"Taylor"
}
if let username = getUsername() {
print("Username is \(username)")
} else {
print("No username")
}
The getUsername()
function returns an optional string, which means it could be a string or it could be nil. I’ve made it always return a value here to make it easier to understand, but that doesn’t change what Swift thinks – it’s still an optional string.
That single if let
line combines lots of functionality:
getUsername()
function.username
constant.So, if let
is a fantastically concise way of working with optionals, taking care of checking and extracting values all at once.
The single most important feature of optionals is that Swift won’t let us use them without unwrapping them first. This provides a huge amount of protection for all our apps, because it puts a stop to uncertainty: when you’re handing a string you know it’s a valid string, when you call a function that returns an integer, you know it’s immediately safe to use. And when you do have optionals in your code, Swift will always make sure you handle them correctly – that you check and unwrap them, rather than just mixing unsafe values with known safe data.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.