Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a type and an explicitly unwrapped type in Swift

This one is really puzzling me: What's the difference between an implicitly unwrapped optional, and the type itself?

For example,

var s:String!
var s2: String

Aren't these two exactly the same? They represent a String that can't be nil, so why on Earth do we need the ! thing?

like image 631
cfischer Avatar asked Feb 11 '23 23:02

cfischer


1 Answers

The implicitly unwrapped optional is an optional, in fact you can assign a nil value

var s: String! = nil

But declaring as implicitly unwrapped, you don't have to append ? every time you use it, so, as its name states, it is implicitly unwrapped because it is supposed to contain a non nil value.

Consequence: if an implicitly unwrapped is nil, most likely when you use it in your code a runtime exception will be generated - for instance:

let s: String! = nil
var s1: String = s // Execution was interrupted, reason: EXC_BAD_INSTRUCTION ...

The question could turn into: why do implicitly unwrapped optionals exist? The answer is that they are needed to Resolving Strong Reference Cycles Between Class Instances, and a few other cases.

I would personally avoid declaring implicitly unwrapped variables in my code, unless I have a very good reason (such as to solve reference cycles, as mentioned above)

like image 98
Antonio Avatar answered Feb 14 '23 12:02

Antonio