Implicitly Unwrapped Optionals

As an ObjC programmer, I despised the introduction of Optionals in Swift.

However, I jumped on the Swift bandwagon on Day 1.

So I understood the basic concepts:

  1. If a value may at some point not have a value, declare it as optional.
  2. If a value has been declared optional, you must test its contents.
    1. You can test with if == nil
    2. You can if let test
    3. Or you can force unwrap

I also read about implicitly unwrapped optionals but I confused them with force-unwrapping.  It also threw me off about when and what to use them for.

Recently I’ve been working on an app that involves a dance between a data holder (AppDelegate), a view (GraphView) and a view controller (GraphViewController).  Plus there is a data setter (Swimming) which kinda complicates things.  These view controllers reside in tabs in the app.  And the functionality works kinda like this:

Swift : Implicitly Unwrapped Optionals iOS8
Swift : Implicitly Unwrapped Optionals iOS8

At the start of the app, the AppDelegate creates an array of data to be plotted (graphArray).  This is needed such that if the user then automatically jumps to the GraphViewController, that array will have a value.

NOTE:True, this could also happen in the GraphViewController’s initWithCoder.  But since Im using the AppDelegate as the data holder, I decided to declare and assign it here.

The user then has the option to go to the SwimmingVC tab or the GraphVC tab.

  • If the user goes straight to the GraphVC tab, it would require a set of values to plot in the graph.  This placeholder data was set in the AppDelegate.
  • If the user goes to the SwimmingVC tab, the real data is fetched from the database and used to set the AppDelegate’s graphArray property.  Essentially this overrides the placeholder data set at the start.

So no matter if the user went straight to the GraphVC or if he stopped by the SwimmingVC to fetch actual data, the GraphView would have a value.

The issue was that I had to define a property in the GraphView class to hold the data.  Again, not strictly following MVC because the View is using a local copy of the data, but that’s what was going on.

So I had to set the GraphView’s graphPoints property to: var graphPoints!

This means that this variable WILL have a value and can be implicitly unwrapped for the remainder of the class code (GraphView), instead of me having to go thru all the code and if/let test each use of self.graphPoints.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s