Member-only story

Avoiding Force Unwrapping in Swift

The Force is only good in Star Wars

--

You might hear that Force Unwrapping is bad and should be avoided at almost any cost. So what is Force Unwrapping, and why is it important?

Photo by NeONBRAND on Unsplash

Oh, and this has nothing to do with the Force. I hope nobody gets confused, or if there are confusing Star Wars images within this article.

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)

Terminology

Compiler: A program that converts the high-level computer program that you write in Xcode, and translates these instructions into machine-code or lower-level form which is executed by the computer

Data Types: The format in which a variable or constant stores data

Optionals: Swift introduced optionals that handle the absence of a value, simply by declaring if there is a value or not. An optional is a type on it’s own!

An Introduction:

Optionals are often seen with the Question Mark ? in Swift:

var myString: String?

Which as a data type is either a String or nil.

To demonstrate this, we can declare the String as optional, and print the output without initialising the String.

var myString: String?

var myString: String?
print (myString) // nil
myString = "Hello, World!"
print (myString) // Optional("Hello, World!"

The optional (?) shows that the compiler cannot be certain if the resultant String is nil or not.

Now for Strings we might not want this to display (for example, we want to just display “Hello, World!” as the text for a label).

--

--

Responses (4)

Write a response