TheeBen TheeBen - 1 month ago 7
Swift Question

What is the difference between weak var: test:UIView! and weak var test:UIView? in outlets?

So I'm trying to do some polishing and profiling on my code written in swift. I have a bunch of questions that are quite detailed and cannot easily find them by searching for the topics such as weak and strong referencing.

For example, I don't see XCode complaining for either of the lines below used for an outlet. I would appreciate if anyone can explain what is the difference if there is any, with respect to keeping weak references and memory management.

@IBOutlet weak var mapTab : MKMapView?


and

@IBOutlet weak var mapTab : MKMapView!


Is it just unwrapping or does it change the nature of the reference?

Answer

The latter is an implicitly unwrapped optional. Whenever it's used, you can think of it as a force unwrap being implicitly done automatically for you. This of course will crash if the value being force unwrapped is nil.

The earlier is a regular optional, so you'll have to deal with unwrapping it yourself, explicitly. You can handle it with guard let, if let, ??, etc. or you can choose to force unwrap it, explicitly, which will behave similar to the first case.