Optionals – A Snag For Every Swift Beginner

Why would something ever be “optional”?

How quickly you grasp the concept of optionals will probably depend entirely on what background you come from. If you have no programming background, you’ll probably be faced with the same question posed by all the other programming concepts you’ve learned, such as variables, functions, loops etc. How is any of this useful? Why would anyone use it? For seasoned programmers in multiple languages, you probably picked it up right away. I came from several years of Python experience, which did very little to prepare me for the concept of optionals. I was put right back to my beginning programming days wondering why anyone would ever need to use such a thing, or how it would ever be considered “powerful”. From various tutorials, I was able to understand the optional concept, but didn’t know how or when I would be using them. So I just started coding. I wasn’t creating my own optionals at all, I didn’t see any reason to. But almost immediately, I came across optionals given to me by the various pre-built things in UIKit (Apple creates these things for developers to build a visual interface, they include UIButton, UITextField, UILabel, etc), and I was struggling with how to get data I wanted inside the optional. Swift won’t let you move on if you don’t deal (handle) with the optional.

Sure, I know about optional handling.

If you’ve done a Swift tutorial, they’ve probably told you the different ways of “handling” an optional. If you’re looking at an optional data type right now, you might have no idea how to get it open properly or why you would choose any one of the different handling options. But in order to pick which one to use, you really need to see them in action before you really can make an informed and intelligent decision. So instead of trying to completely grasp how to use optionals like a pro before ever using them (which makes no sense, when you really think about it), just do the easiest one, it’s called a “Force Unwrap”. You put an exclamation point at the end of the optional to “unwrap” it and get whatever’s inside, in this simple example it’s a string:

let myOptional:String? = "this is the string inside my optional."
let myString = myOptional!

If you’re new to optionals, just use this one. Yes, it’s “dangerous”, a word that requires a grasp of the concept of optionals to understand, but it’ll get at the data you want and you can move on with your coding. “Dangerous” would be if you had released your app on the App Store to real people, and you used this method of optional handling everywhere in your app. But let’s be real – if you’re wondering how to do the optional thing, like I was, you’re nowhere near releasing your app to the App Store. Just live life simply and dangerously, and use Force Unwrapping. Starting with the simplest and easiest option to understand will let you get your feet wet with them, and you’ll eventually see why you need the other options.

The nothing problem

It took me a long time to grasp the idea of the problem of nothing, or nil in Swift, for programming languages. Starting with a “high-level” language like Python, so much is handled for you in the background with features like garbage collection and dynamic data typing. What I came to realize was that when you’re building your app, you’ll reach a point where you do something that may get the result you wanted, or it may not. A lot of times the in the “may not” scenario, the result will be placed in an optional and the contents will be “nil”. For instance, building on the example above, let’s say you had a login screen and you wanted to get the user’s email address in order to log in. You might have a text field to allow the user to type their email address.

let myTextField = UITextField()
let myString = myTextField.text!
login(with: myString) //Not a real function. it just illustrates my point.

As it turns out, the “text” property of a UITextField, which should contain text the user typed, is an optional string. To unwrap it, put a “!” at the end of it. Then log the user in with the fictional “login” function (pseucode, as it’s called). Why an optional? Why not just make it a string and make it easier for everyone? The answer is because you have no idea what the user is going to put, or not put, in that field. It could be something, it could be nothing. But if you just use a Force Unwrap, and test logging in without typing anything in your field, your app crashes, saying something about unexpectedly getting nil. That’s the crux of the problem that optionals solve. Computers don’t like nothing. Apparently in some older languages there are not elegant tools such as optionals for dealing with nothing, and applications just crash a lot (a gross oversimplification, sorry to any programmers in said older languages). An optional allows you to deal with the nothing and prevent a crash.

Dealing with nothing

If your app is crashing when you get text from a text field, and you don’t want it to crash and you would rather tell the user, “Hey, please don’t put nothing in this field!”, that’s a good time to use a different optional handling method. There are several other methods, but I’m not going to explain them all, because you just need to work with them to understand. The Internet might get mad at me, because it seems like this is where most people introduce optional binding, which I found to be really difficult to understand. But I think this method, while really wordy, makes it clear what is happening, and keep your app from crashing:

let myTextField = UITextField()
if myTextField.text == nil {
    tellUserToTryAgain()  //Not a real function. it just illustrates my point.
    let myString = myTextField.text!
    login(with: myString) //Also not real. See above about my point.

If you understand “if” in Swift, and you can just check the text in the text field to see if it’s nil, like I did above. If it is, I again used a fictional function “tellUserToTryAgain”, to tell the user not to login with nothing. If myTextField.text does indeed contain text, we can “safely” Force Unwrap it, and grab the text, and use my fictional “login” function to login.

Advanced optionals

Everything else for handling optionals would fall into a category of handling options that I would consider advanced. Once you have spent a significant amount of time working with optionals, you can consider Optional Binding, Optional Chaining and Nil Coalescing. They solve more abstract problems, and I really think you have to work with optionals on a really basic level for a while before you get the use cases for the advanced stuff. At least I did, and unlike most programmers I’m not a super genius so stuff takes a while to sink in.

Happy programming!

1 Comment Optionals – A Snag For Every Swift Beginner

  1. Pingback: Optionals – The Pyramid of Doom | JBA

Leave a Reply

Your email address will not be published.