• Michael Craun

Handling Optional Values


Good morning, fellow code junkies! Today's lesson is going to be about something every aspiring developer will find useful: handling optional values. An optional value is defined as a value that may or may not exist.

Some functions or methods you may encounter or even create along your way might return what is called an optional value. For instance, you might create something like the code below. The function in the example code snippet checks userInput against the Option enum and returns an optional value of type Option if userInput matches one of two possible options. Otherwise, it returns nil.

Alternatively, when your users are presented with things like UITextFields or UITextView's, they don't have to enter anything, hence these values being optional. If you know what you're doing, optional values are easy to handle. Hopefully, by the end of this lesson, you'll understand a little more about handling optional values.

We're going to be taking a look at handling optional values from user input, today. Handling optional values from function returns and handling optional values from user input is done in pretty much the exact same fashion, so let's get into it. As always, I've set up a starter project, which you can download here. Alternatively, you can set up your own project with two UITextFields, a UIButton, and a UILabel. The UITextFields and UILabel need IBOutlets, whereas the UIButton needs an IBAction linked to them. When you're done, your ViewController should look something like this:

VIEWCONTROLLER

We'll only be working in the ViewController.swift file for today's lesson, so let's hop right in. The first thing we'll do is create a variable right under our IBOutlets called usersName, which is of type String. Next, in our viewDidLoad, we'll set the delegate of both of our UITextFields equal to our ViewController (self).

This will cause an error, so let's create an extension of ViewController that conforms to UITextFieldDelegate. Within this extension, we're going to call the UITextFieldDelegate method textFieldDidBeginEditing(_:) and set outputLabel.text equal to an empty String. This will cause the outputLabel to "reset" when the user selects either of the UITextFields.

Alright. If we build and run the project right now and click the done button, nothing happens. Let's start modifying the donePressed(_:) IBAction we've created and start handling our optional user input! We want our app to require a first name to register, but we want the last name to be optional. How do we do this? Well, let's take a look. The first option we have is force unwrapping the optional user input, using the ! operator. Let's try this out by putting the following lines into our donePressed(_:) IBAction:

let firstName = firstNameField.text!

print(firstName)

Build and run, enter a first name and tap the done button, and you'll see your input printed out in the console! Remember, though, that we're trying to handle optional user input. So, what happens if the user doesn't input a first name? Give it a try. Aaaaaaaand... You got a crash, didn't you? This crash happened because we're unwrapping an optional value without checking to see if there's anything there. Let's go ahead and erase those last two lines and replace them with something a little smarter, such as these lines:

guard let firstName = firstNameField.text, firstName != "" else {

return

}

usersName = firstName

print("FIRST NAME: \(firstName)")

Now, when you follow the same steps as before, you find that when you input nothing, the app doesn't crash, but also doesn't print anything. That's because the guard let we used checks to see if there's anything in the firstNameField and, if there isn't, exits the function by using the return keyword. This is great, but what can we do with this information. Let's add one more line, right before the return inside the guard let, like so:

outputLabel.text = "Please enter at least a first name to register..."

Great! After that, we're going to set our String value, usersName, equal to firstName. Next we'll check if the user has input a last name or not. Easy enough, just force unwrap it, right? Because that turned out so swell the last time... No, instead, we're going to try a different method of safely unwrapping an optional value, called an if let. Insert the following lines of code into your donePressed(_:) function:

if let lastName = lastNameField.text, lastName != "" {

print("LAST NAME: \(lastName)")

usersName += " \(lastName)"

}

This if let check the lastNameField to see if there's any input there. If there is, it appends our String value, usersName, with this information. Otherwise, it continues through to the next step of the function.

Something to note: This is probably the biggest difference between a guard let statement and an if let statement: A guard let statement allows for the variable declared within it to be used later within the function, whereas an if let statement does not. This means that if you need to check for user input and use it somewhere else in the function, you should use a guard let. Otherwise, you should use an if let. Additionally a guard let statement also allows you to complete a certain task, such as displaying an alert to the user, if the optional value isn't "up to par." This can be accomplished with an if let statement, but requires additional lines of code, which eats up more system resources.

Alright, finally, we need to have something to show the user that their input was accepted and they have successfully "registered." Let's use the tools we have and set the output label's text, like so:

outputLabel.text = "Welcome to Optionals, \(usersName)!"

We should be done, and your ViewController.swift file should look something like this:Let's build and run our project, and play around with things in here. You should see that your output label updates appropriately when you enter nothing, just a first name, just a last name, and both a first name and last name!

Well, that's it for this lesson. As always, you can download a finished project here, if you just want to play around with it and see if you can figure it out yourself. Until next time, code junkies!

Happy coding,

Michael Craun

#Programming #iOS #Optionals

2 views0 comments

Recent Posts

See All

Week 2 - Getting Help

put your faith in God. I know it seems easy, cliche even, or perhaps you don’t see how that can help with the situation.