-1

I am using playground to run the below code

var a : Int!
a = nil
print(a) o/p - none
print(a!) o/p - crash

a = 5
print(a) o/p - some(5)
print(a!) o/p - 5 

I know optionals is enum and it has two type none or some. But as I am declaring a as implicitly unwrapped I think I don't have to unwrap it to get the actual data. Whether I have understood optionals wrong ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Aditya Srivastava
  • 2,630
  • 2
  • 13
  • 23
  • 7
    Essentially a duplicate of https://stackoverflow.com/q/49609528/1187415 – IUOs are regular optionals now, only with special properties to unwrap *if necessary,* see also https://stackoverflow.com/q/39537177/1187415 and https://stackoverflow.com/q/39633481/1187415 – Martin R May 22 '18 at 12:21
  • 4
    Also, using print is very misleading. Replace it with a function that takes an `Int` parameter to really see what's going on. – Gereon May 22 '18 at 12:23
  • In particular, `print` automatically casts `Optional` to `Any`, which means `a` no longer needs to be unwrapped in order to be printed. Force unwrapping still crashes, though. – BallpointBen May 22 '18 at 12:34

2 Answers2

1

As others have said, IUOs (implicitly unwrapped optionals) are now regular optionals with some hints to the compiler that gives it permission to unwrap them.

That being said, print is handled differently. Try using an assignment to a non-optional variable instead. That's a better test, e.g:

var a : Int! = nil
let b: Int = a
Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

Here’s a use case for implicitly unwrapped optionals. In any class, all properties have to be initialised upon initialisation of the class instance. You can either assign the properties a default value or use the init function for property initialisation.

In a view controller, however, you don’t want to use an init function. Some properties might not have default values but will rather be initialised during viewDidLoad. In this case you could declare the property as implicitly unwrapped because it won’t be accessed before view controller loading—and after that you can make sure in viewDidLoad (or in the calling view controller’s prepareForSegue method, for example) that it is not nil, hence safe to be accessed from now on.

Just my two cents to add to your understanding of IUOs.

Tom E
  • 1,530
  • 9
  • 17