Swift Known Unknowns: Is swift force unwrapping bad?
By: Murali Krishnan
Tags: iOS App Development, Swift Programming, Optionals, iOS, Swift

When swift was introduced initially if there was one thing that sounded alien to Objective-C developers it was the concept of Optionals and whats the best way to unwrap it.

Before going into the ways to unwrap an Optional it’s best to see what an optional is for its face value leaving behind all the confusion with !, ? and ??.

@frozen public enum Optional<Wrapped> : ExpressibleByNilLiteral { case none case some(Wrapped) }

An optional is a simple enum which can take one of two values, either nil or some value which is a generic type. The speciality of optional is that it can be assigned ‘nil’ which denotes the absence of a value. We can see the Optional conforms to protocol ExpressibleByNilLiteral which enables any type to be initialized with nil. This is what makes it possible for Optionals act as a box which either hold a nil or an actual value.

public protocol ExpressibleByNilLiteral { /// Creates an instance initialized with `nil`. init(nilLiteral: ()) }

We can use Optionals in our code as below:

var optionalInt: Optional<Int> = Optional.none optionalInt = Optional.some(42)

Thanks to swift shorthand we can declare it a simple and elegant way.

var optionalInt: Int? optionalInt = 42

This value can be safely unwrapped using a conditional check in one of the following ways.

Optional Binding:

To conditionally bind the wrapped value of an Optional instance to a new variable, use one of the optional binding control structures, including if let , guard let , and switch .

Optional Chaining

To safely access the properties and methods of a wrapped instance, we can use the postfix optional chaining operator (postfix ? ). The following example uses optional chaining to access the hasSuffix(_:) method on a String? instance.

Using the Nil-Coalescing Operator

We can provide a default value using the nil-coalescing operator(??) if the value is nil.

let validInt = optionalInt ?? 0

Unconditional Unwrapping

When you’re certain that an instance of `Optional` contains a value, you can unconditionally unwrap the value by using the forced unwrap operator (postfix `!`). This is what we will focus on for today.

let validInt = optionalInt!

Force unwrapping is a useful tool and it is sometimes debatable whether it’s a good programming practice. Some do it all the time and some never do it. The main reason why some developers never do it is because the app terminates if the value if found to be nil on force unwrapping. But it might not be as bad as it sounds.

For any swift class or struct, all stored properties have to be provided a value in the initializer. The only way to get around this is to declare it as an optional. This is the reason why any IBOutlet is declared as an optional as we don’t have this value in the initializer. One more thing to notice is that this value is implicitly unwrapped. We don’t have to unwrap it while using in the code because we know that the value will be present by the time we are using it in our viewDidLoad or any other methods later.

@IBOutlet weak var sampleLabel: UILabel!

Even the AppDelegate has an optional UIWindow property, but if this value is nil, then there is something wrong with our code.

optional var window: UIWindow? { get set }

Force unwrapping can be used to detect these corrupt states of application and can prevent the app from running in an unexpected state. In some conditions force unwrapping might be the most sensible thing to do, if the value you are looking for is absolutely critical for your app. On a lighter note, force subscripting is only as dangerous as array subscripting is, if you use it the right way.