|< How is protocol-oriented programming different from object-oriented programming?||Why does Swift make us unwrap optionals? >|
Swift’s optionals are one of its most powerful features, while also being one of the confusing. Their core job is simple: they allow us to represent the absence of some data – a string that isn’t just empty, but literally doesn’t exist.
Any data type can be optional in Swift:
nil– it might not exist.
Userstruct could contain all sorts of properties that describe a user.
Userstruct could contain all those same properties, or not exist at all.
Making that distinction between “it could be any possible value for that type” and “it could be nil” is the key to understanding optionals, and it’s not easy sometimes.
For example, think about Booleans: they can be true or false. That means an optional Bool can be true, false, or neither – it can be nothing at all. That’s a little hard to grasp mentally, because surely something is always true or false at any given time?
Well, answer me this: do I like chocolate? Unless you’re a friend of mine or perhaps follow me very closely on Twitter, you can’t say for sure – you can’t definitely say True (I like chocolate) or False (I don’t like chocolate), because you just don’t know. Sure, you could ask me and find out, but until you do so the only safe answer is “I don’t know”, which in this case could be represented by making the Boolean an optional with a nil value.
This is also a bit confusing when you think about empty strings, “”. That string contains nothing, but that isn’t the same thing as nil – an empty string is still a string.
When you’re learning, optionals can feel really painful – you might think Swift doesn’t need them, you might think they just get in the way, and you might grind your teeth every time you have to use them. But please trust me on this: after a few months they will make perfect sense, and you’ll wonder how you survived without them!
For another perspective on optionals, check out this video from Brian Voong: https://www.youtube.com/watch?v=7a7As0uNWOQ
SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!
Link copied to your pasteboard.