0

What are the differences when i unwrap Optional value by ? and !

If there is Class name A and there is a property name proA

Then if i make an instance like this

var a:A? = A()
a?.proA
a!.proA

I can approach property 'proA' two ways above. I know I cannot get value if I use a.proA because a is a Optional Type.

Also, I know a!.proA can get value because it unwrap the value in force

And what is a?.proA?

What are the differences between a?.proA and a!.proA

nayem
  • 7,285
  • 1
  • 33
  • 51
PrepareFor
  • 2,448
  • 6
  • 22
  • 36
  • `a?` is calling proA so that may be `a` is nil, here we notify to the compiler by `?` for the `a`. If the compiler will get nil it goes silently without crashing – Salman Ghumsani Jul 24 '17 at 06:11

1 Answers1

1

As you stated, ! forcefully unwraps the optional.

  var a: A? = A()
  a!.prop

However, what happens if the optional was never assigned a value, which means it's nil?

  var a: A?;
  a!.pop

You get a Swift runtime error (think of it as the equivalent of a null pointer exception in other languages e.g. Java).

On the other hand, if you use ?, you can take advantage of optional chaining. This allows you to gracefully traverse optional properties without fear of causing a runtime error. If some intermediate property along the chain is nil, the whole expression will return nil.

 var a: A?;
 a?.pop //returns nil, no runtime error
Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
Josh Hamet
  • 957
  • 8
  • 10