All you should know about ImplicitlyUnwrappedOptional in Swift 3.x

Before diving into the topic, lets refresh our knowledge. To understand ImplicitlyUnwrappedOptional a.k.a. IUO, you should know what are Optional variables. If you already have an understanding of what Optional variables are , you can checkout my previous post on Optional linked below.

Lets start…
Swift comes with capabilities of being type safe and Optional variables are one of the ways in making Swift type safe.
In Swift, Optional has two types:

  1. Optional
  2. ImplicitlyUnwrappedOptional

We are going to focus on ImplicitlyUnwrappedOptional(IUO) in this post. You are curious to know, what are these IUOs?

As you already know, when we declare a variable or constant to be Optional, it indicates that variable or constant can have “no value”. So, we need a check to unwrap the Optional to use the value stored in it. As you can see below in the code:

var someOptionalString: String? 
if someOptionalString != nil {    
print("someOptionalString = \(someOptionalString!)")
} else {
print("someOptionalString is nil")
}

This leads to overhead of checking the Optional, before being able to use its value every time in the program. But if we know, that an Optional will always have value, then what is the point of having this overhead.

To eliminate this overhead, we have ImplicitlyUnwrappedOptional, because it allows you to access optional value without unwrapping it every time.
It has a special syntax with ! at the end of type instead of ? used in Optional:

var assumedString: String! = "Some assumed string"
print(assumedString) // Some assumed string

Now, you may be thinking, same thing you can achieve with Non-Optional String variable. What is the point of introducing another mind boggling concept?

Well, To understand this let us take in to account another example also called deferred initialisation pattern:

struct S {
var x: Int!
init() {}
func initLater(x someX: Int) {
x = someX
}
}

Here we use x as ImplicitlyUnwrappedOptional because we don’t want to have overhead of unwrapping x each time we access this property. But it is clear from the code that we don’t know the value of x at the time of declaration, but we are sure that it will contain value later on in the program, before we access this value of x. In this case, use of non optional variable is not valid as we don’t know the value of x at the time of declaration. This is one of the use case, why ImplicitlyUnwrappedOptional is introduced as we can’t set non optional to nil.

Fair enough. But with this advantage, comes another disadvantage. Let’s take in to account below example:

func f(i: Int) -> Int! {
return (i > 0) ? i : nil
}
let a = f(i: 0)
print(a) // crash! as 'a' is nil

Another big problem. How to solve it?
Swift 3.x, comes with a magic to save you from this problem, (which you have to understand), to better utilize ImplicitlyUnwrappedOptional.

This is the core of this post.

In Swift 3.x, for the above code, Swift compiler will show you some warnings.

This comes with an increased type safety. Swift 3.x implicitly returns usual Optional from function that is expected to return ImplicitlyUnwrappedOptional, unless we explicitly declare, we want ImplicitlyUnwrappedOptional.

From the above screenshot, you can see that type of a is Optional<Int> instead of expected ImplicitlyUnwrappedOptional<Int>.

This is one of the biggest change in the implementation of ImplicitlyUnwrappedOptional.

Now, type inferences is no longer unsafe, until we explicitly want it to be unsafe.

Now, a is ImplicitlyUnwrappedOptional<Int> but c is Optional<Int>, thereby saving us from accidently injecting unsafeImplicitlyUnwrappedOptional into our code.

Note: It helps Swift to interact with APIs for whom nullability is meaningful or the return type cannot be known mainly
with Objective-C API.

Edit: Forget to share this important piece of information, how Chris Willmore proposed this new change about ImplicitlyUnwrappedOptional.

If you like the post, hit the ❤️ button and spread the word.
Comment below to give your feedback and help me improve the content.