Something weird with IUO?

I am missing something somewhere ...

But I would believe that this code would have to crash :

import Foundation

class Test {
  let hello: String!
  
  init() {
   hello = nil
  }
  
  func check() {
    print(hello.debugDescription)
  }
}

let h = Test()
h.check()

But it does not crash, and produce the string :

nil

That is the expected behavior. With the implementation of SE-0054 Abolish ImplicitlyUnwrappedOptional type, let hello: String! declares a regular (strong) optional String? with an additional attribute indicating that its value may be implicitly unwrapped. For example,

print(hello.count)

would crash because accessing the count property of String forces the compiler to unwrap the optional. But that is not necessary in

print(hello.debugDescription)

It calls the debugDescription method on String?, which here prints "nil".

There is also a good explanation on Stack Overflow, with examples.

3 Likes

Ok, thank for the explanation, still seems weird to me, because it seems that I unwrap the ivar hello in this case also ... to access the ivar debugDescription

Well, ok, sorry, I see the mistake I do ... in my view of the optional ivar