Why create “Implicitly Unwrapped Optionals”, since that implies you know there’s a value?

i0S Swift Issue

Question or problem with Swift language programming:

Why would you create a “Implicitly Unwrapped Optional” vs creating just a regular variable or constant?
If you know that it can be successfully unwrapped then why create an optional in the first place?
For example, why is this:

let someString: String! = "this is the string"

going to be more useful than:

let someString: String = "this is the string"

If ”optionals indicate that a constant or variable is allowed to have ‘no value’”, but “sometimes it is clear from a program’s structure that an optional will always have a value after that value is first set”, what is the point of making it an optional in the first place?
If you know an optional is always going to have a value, doesn’t that make it not optional?

How to solve the problem:

Solution 1:

Consider the case of an object that may have nil properties while it’s being constructed and configured, but is immutable and non-nil afterwards (NSImage is often treated this way, though in its case it’s still useful to mutate sometimes). Implicitly unwrapped optionals would clean up its code a good deal, with relatively low loss of safety (as long as the one guarantee held, it would be safe).

(Edit) To be clear though: regular optionals are nearly always preferable.

Solution 2:

Before I can describe the use cases for Implicitly Unwrapped Optionals, you should already understand what Optionals and Implicitly Unwrapped Optionals are in Swift. If you do not, I recommend you first read my article on optionals

When To Use An Implicitly Unwrapped Optional

There are two main reasons that one would create an Implicitly Unwrapped Optional. All have to do with defining a variable that will never be accessed when nil because otherwise, the Swift compiler will always force you to explicitly unwrap an Optional.

1. A Constant That Cannot Be Defined During Initialization

Every member constant must have a value by the time initialization is complete. Sometimes, a constant cannot be initialized with its correct value during initialization, but it can still be guaranteed to have a value before being accessed.

Using an Optional variable gets around this issue because an Optional is automatically initialized with nil and the value it will eventually contain will still be immutable. However, it can be a pain to be constantly unwrapping a variable that you know for sure is not nil. Implicitly Unwrapped Optionals achieve the same benefits as an Optional with the added benefit that one does not have to explicitly unwrap it everywhere.

A great example of this is when a member variable cannot be initialized in a UIView subclass until the view is loaded:

class MyView: UIView {
    @IBOutlet var button: UIButton!
    var buttonOriginalWidth: CGFloat!

    override func awakeFromNib() {
        self.buttonOriginalWidth = self.button.frame.size.width
    }
}

Here, you cannot calculate the original width of the button until the view loads, but you know that awakeFromNib will be called before any other method on the view (other than initialization). Instead of forcing the value to be explicitly unwrapped pointlessly all over your class, you can declare it as an Implicitly Unwrapped Optional.

2. When Your App Cannot Recover From a Variable Being nil

This should be extremely rare, but if your app can not continue to run if a variable is nil when accessed, it would be a waste of time to bother testing it for nil. Normally if you have a condition that must absolutely be true for your app to continue running, you would use an assert. An Implicitly Unwrapped Optional has an assert for nil built right into it. Even then, it is often good to unwrap the optional and use a more descriptive assert if it is nil.

When Not To Use An Implicitly Unwrapped Optional

1. Lazily Calculated Member Variables

Sometimes you have a member variable that should never be nil, but it cannot be set to the correct value during initialization. One solution is to use an Implicitly Unwrapped Optional, but a better way is to use a lazy variable:

class FileSystemItem {
}

class Directory : FileSystemItem {
    lazy var contents : [FileSystemItem] = {
        var loadedContents = [FileSystemItem]()
        // load contents and append to loadedContents
        return loadedContents
    }()
}

Now, the member variable contents is not initialized until the first time it is accessed. This gives the class a chance to get into the correct state before calculating the initial value.

Note: This may seem to contradict #1 from above. However, there is an important distinction to be made. The buttonOriginalWidth above must be set during viewDidLoad to prevent anyone changing the buttons width before the property is accessed.

2. Everywhere Else

For the most part, Implicitly Unwrapped Optionals should be avoided because if used mistakenly, your entire app will crash when it is accessed while nil. If you are ever not sure about whether a variable can be nil, always default to using a normal Optional. Unwrapping a variable that is never nil certainly doesn’t hurt very much.

Solution 3:

Implicitly unwrapped optionals are useful for presenting a property as non-optional when really it needs to be optional under the covers. This is often necessary for “tying the knot” between two related objects that each need a reference to the other. It makes sense when neither reference is actually optional, but one of them needs to be nil while the pair is being initialized.

For example:

// These classes are buddies that never go anywhere without each other
class B {
    var name : String
    weak var myBuddyA : A!
    init(name : String) {
        self.name = name
    }
}

class A {
    var name : String
    var myBuddyB : B
    init(name : String) {
        self.name = name
        myBuddyB = B(name:"\(name)'s buddy B")
        myBuddyB.myBuddyA = self
    }
}

var a = A(name:"Big A")
println(a.myBuddyB.name)   // prints "Big A's buddy B"

Any B instance should always have a valid myBuddyA reference, so we don’t want to make the user treat it as optional, but we need it to be optional so that we can construct a B before we have an A to refer to.

HOWEVER! This sort of mutual reference requirement is often an indication of tight coupling and poor design. If you find yourself relying on implicitly unwrapped optionals you should probably consider refactoring to eliminate the cross-dependencies.

Solution 4:

Implicitly unwrapped optionals are pragmatic compromise to make the work in hybrid environment that has to interoperate with existing Cocoa frameworks and their conventions more pleasant, while also allowing for stepwise migration into safer programing paradigm — without null pointers — enforced by the Swift compiler.

Swift book, in The Basics chapter, section Implicitly Unwrapped Optionals says:


Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties.

You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it is used. Rather than placing an exclamation mark after the optional’s name each time you use it, you place an exclamation mark after the optional’s type when you declare it.

This comes down to use cases where the non-nil-ness of properties is established via usage convention, and can not be enforced by compiler during the class initialization. For example, the UIViewController properties that are initialized from NIBs or Storyboards, where the initialization is split into separate phases, but after the viewDidLoad() you can assume that properties generally exist. Otherwise, in order to satisfy the compiler, you had to be using the
forced unwrapping,
optional binding
or optional chaining
only to obscure the main purpose of the code.

Above part from the Swift book refers also to the Automatic Reference Counting chapter:


However, there is a third scenario, in which both properties should always have a value, and neither property should ever be nil once initialization is complete. In this scenario, it is useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class.
This enables both properties to be accessed directly (without optional unwrapping) once initialization is complete, while still avoiding a reference cycle.

This comes down to the quirks of not being a garbage collected language, therefore the breaking of retain cycles is on you as a programmer and implicitly unwrapped optionals are a tool to hide this quirk.

That covers the “When to use implicitly unwrapped optionals in your code?” question. As an application developer, you’ll mostly encounter them in method signatures of libraries written in Objective-C, which doesn’t have the ability to express optional types.

From Using Swift with Cocoa and Objective-C, section Working with nil:


Because Objective-C does not make any guarantees that an object is non-nil, Swift makes all classes in argument types and return types optional in imported Objective-C APIs. Before you use an Objective-C object, you should check to ensure that it is not missing.
In some cases, you might be absolutely certain that an Objective-C method or property never returns a nil object reference. To make objects in this special scenario more convenient to work with, Swift imports object types as implicitly unwrapped optionals. Implicitly unwrapped optional types include all of the safety features of optional types. In addition, you can access the value directly without checking for nil or unwrapping it yourself. When you access the value in this kind of optional type without safely unwrapping it first, the implicitly unwrapped optional checks whether the value is missing. If the value is missing, a runtime error occurs. As a result, you should always check and unwrap an implicitly unwrapped optional yourself, unless you are sure that the value cannot be missing.

…and beyond here lay dragons

Solution 5:

One-line (or several-line) simple examples don’t cover the behavior of optionals very well — yeah, if you declare a variable and provide it with a value right away, there’s no point in an optional.

The best case I’ve seen so far is setup that happens after object initialization, followed by use that’s “guaranteed” to follow that setup, e.g. in a view controller:

class MyViewController: UIViewController { var screenSize: CGSize? override func viewDidLoad { super.viewDidLoad() screenSize = view.frame.size } @IBAction printSize(sender: UIButton) { println("Screen size: \(screenSize!)") } } 

We know printSize will be called after the view is loaded — it’s an action method hooked up to a control inside that view, and we made sure not to call it otherwise. So we can save ourselves some optional-checking/binding with the !. Swift can’t recognize that guarantee (at least until Apple solves the halting problem), so you tell the compiler it exists.

This breaks type safety to some degree, though. Anyplace you have an implicitly unwrapped optional is a place your app can crash if your “guarantee” doesn’t always hold, so it’s a feature to use sparingly. Besides, using ! all the time makes it sound like you’re yelling, and nobody likes that.

Hope this helps!