I hope you can recognize that Swift takes code safety seriously. This takes a number of forms, of which the most important ones are:
Int
or String
. There is a special Any
type, used when you want to mix data together, but even then you’ll need to typecast values back to Int
or whatever in order to use them.!
is sometimes called “the crash operator”.switch/case
block, it must be exhaustive – it must cover all possible cases.Let’s take another look at some optional code. Consider this:
var a: Int? = 5
var b: Int? = 10
That creates two variables, a
and b
, both of which store optional integers. That means they might contain a number like 0, 10, 2309832, or they also be nil – they might have no value at all. How would you add those two numbers together?
Remember: Swift doesn’t let you use optionals directly; you need to unwrap them safely first. This is because they can be nil, and “5 + nil” is undefined behavior that used to crash your app or produce weird behavior before Swift came along with its optionals.
In this case, we can unwrap a
and b
using if let
. This creates new constants that are regular integers rather than optional, so we can work with them directly:
if let unwrappedA = a {
if let unwrappedB = b {
let c = unwrappedA + unwrappedB
}
}
That let c
line will only be reached if both a
and b
had a value, so Swift knows it’s safe to run.
Swift lets you merge those two if let
statements into one, like this:
if let unwrappedA = a, let unwrappedB = b {
let c = unwrappedA + unwrappedB
}
While that’s common practice, I prefer to avoid it in this book because it’s a bit harder to read.
Another important take-away is that Swift is a modern programming language. It used many of the latest development techniques when it launched, as has since evolved further. This means we benefit from great features like optionals, closures, switch/case
ranges, and more.
Finally, I hope you feel like you’re able to go back to the playground now and start writing a little of your own code. Sure, there’s no iOS code yet, but you can still have a go at attempting the challenge below.
BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.