Implicitly Unwrapped Optional


As you have checked in the last article in which you have learned about the Optional, Optional value and Optional binding. Want to recall here you go - Take a look!

Sometimes you are sure when an optional has a value when it is set very first time. So it’s not necessary to check the if condition and unwrap the optional value for every time when you want to use that value. Because as you will be assuming that there is a value.

So these kinds of optional defined as Implicitly unwrapped optional. So we use (!) to put in place of (?) right after the value which you want to make as optional.

The primary use of implicitly unwrapped optional during the class initialization. As you might initial an optional value with some value or default value so. Example:


let optionalString: String? = "optional"

let forcedUnwrappedString: String = optionalString!

above line of code clearly, states we are storing the optional string in 'optionalString' and then we are using forced unwrapping to read that optional value.
let sampleString: String! = "implicitly unwrapped optional string."
let implicitString: String = sampleString

Clear from above lines, we created the implicitly unwrapped optional string and while reading we do not require anything. Just use that value as it is. As stated above for implicitly unwrapped optional we will use the ‘!’ in the place of ‘?’ and that what we did. 
But you need to careful fun everytime and implicitly unwrapped optional value is same as normal optional value so you have to very sure that it does have value. If value does not exists and you try to use implicitly unwrapped optional value as it will cause your program crash. So be safe and have a check always or optional binding and save your life!!

if sampleString != nil {
    print(sampleString)
}

So the bottom line is made constant or variable as implicitly unwrapped optional when you are 100% sure about its value will always exist.
Hope above notes will give you a clear about for implicitly unwrapped optional. Please, do comment and give your valuable feedback. You can my other post.

Comments

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Closures in Swift - Part 1