Learn iOS with Examples, Code Snippets and Video Tutorials

Swift Basics – Part 2 – Variables, Optionals and Forced Unwrapping

Swift Basics – Part 2 – Variables, Optionals and Forced Unwrapping
October 15, 2014 Justin

In this video tutorial,  we’ll look at creating variables in a Playground file. Initially we’ll just look at  number types, like Int, Double, Float, then Strings.  And then we’ll tackle the question on every new Swift learner’s mind, “what’s up with Optionals?”

If you want to skip the video and take a quick look at some of the code, have a gander below.

At #1  we create a variable named shameLessPlug. Since we are not giving it a specific value from the start,  we  can put a question mark after the type, which basically says “this could be nothing”,  or nil.  Which it is since it has no value.  Testing whether or not a variable is nil or actually has a value is a big part of programming.

At #2 we write an if statement which tests shameLessPlug to see if it is nil or not.  Notice the question mark is back again since the value of the variable is considered an Optional.  Since this is true, the code inside the opening and closing brackets, will run. At this point, we do give shameLessPlug a value, and the ? isn’t required here.

At #3 we create a constant (notice the word let instead of var) called message which will be used to combine together our shameLessPlug variable and some more text.  Constants are like variables, but they don’t change value over time. It will always equal whatever value we initially set.

This time notice the ! after shameLessPlug.  The exclamation mark following a variable in Swift means we are forcibly unwrapping it’s value.  We’re telling the compiler “Hey we’re so confident this has a value, you’ll have no problem using it”.   If the variable was still nil though, the program would crash.

As I mention in the video, don’t feel like you need to shy away from using the ! instead of the ? in Swift. In some cases, you absolutely have to use the exclamation mark. In other cases, you can safely get away with one or the other.

Continue to Part 3


Justin Dike is the owner and lead developer at CartoonSmart.com. He's taught hundreds of hours of game development video tutorials, covering everything from coding to art. These days he's working mostly on Swift and Sprite Kit tutorials, which often lead into highly polished iOS / tvOS Starter Kits, which require no programming at all, but are capable of making nearly any type game! Yeah, you read that write. You can also find Justin at the official CartoonSmart Podcast


Leave a reply

Your email address will not be published. Required fields are marked *


Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com