Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Xcode make outlets unowned instead of weak?

Xcode produces outlets as weak vars with implicit unwrapping, like this:

@IBOutlet weak var nameTextField: UITextField!

I wonder why it didn't just make onowned var, which - in my understanding - behaves exactly the same, but keeps the type non-optional. Is there any difference between these two?

weak var foo: UITextField!
unowned var foo: UITextField
like image 987
Robo Robok Avatar asked Jan 21 '26 02:01

Robo Robok


1 Answers

A weak variable has a default value, namely nil, so your code is legal because the outlet property has a value at object creation time (before the outlet is actually connected).

But an unowned variable would have no default value and your code wouldn't compile. Try it.

Also the entire concept would be wrong. unowned is for a thing with a guaranteed independent existence and which you can't live without. A subview of a view controller's view satisfies neither of those.

like image 184
matt Avatar answered Jan 23 '26 20:01

matt