Why use unowned when you can use weak? [duplicate] - swift

This question already has answers here:
What is the difference between a weak reference and an unowned reference?
(7 answers)
Closed 8 years ago.
In Swift, there is option to use unowned or weak. Why use unowned when you can use weak? It seems the two are almost the same, with weak being safer.

Apple says that the rules are as follows:
Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime.
Use an unowned reference when you know that the reference will never be nil once it has been set during initialization.
The reason for having unowned in the first place is that weak must be of an optional type, while unowned will be non-optional. This lets you avoid unwrapping and/or checking, which is associated with variables of optional type.
Both kinds of references carry the same costs: Swift keeps track of them, so that it could set weak references to nil, and mark unowned references invalid when the object they reference is destroyed.

Related

Understanding weak and unowned reference in Swift under the hood

I want fully understand what going inside weak and unowned referance in Swift.
For this i read MikeAsh and got some questions.
What already known:
when there is no weak (and, i suppose, unowned) object reference, the strong reference counter is stored directly in the memory area of the object
when a weak link appears, the second word in the object memory is reused to reference the side table
side table has link to the object
weak link refers to this side table
And what i want to clearify:
What else side table store inside except link to the object and number of strong reference?
Is unowned reference link to the side table too? If not and unowned link refers to the object memory what about performance between weak and unowned ?
Okay, i found out.
Unowned link points to the object as well as strong.
Unowned link faster than weak.
Side table stores strong RC, weak RC, unowned RC, link to the object and some flags

Optional unowned reference versus weak in Swift 5.0

This is allowed in Swift 5.0:
class Person {
unowned var child: Person?
}
This is supported by this release notes:
unowned and unowned(unsafe) variables now support Optional types.
(47326769)
I understood exactly the difference between weak and unowned in Swift 4.2 and before. However, I am not sure why Apple decided to make the unowned an optional type. Even in the docs (which are docs for Swift 5.0) this implemented 'proposal' (where can I even find that proposal with the motivation to add optional unowned references?) isn't updated, because it says:
An unowned reference is expected to always have a value. As a result,
ARC never sets an unowned reference’s value to nil, which means that
unowned references are defined using non-optional types.
Above isn't true anymore. The only functional difference that Apple states is that an unowned reference is expected to have an equal or longer lifetime than the object holding that reference. Well, I am curious about the technical use of this.
What difference does it make when I use a weak reference vs an optional unowned reference? Or is the only difference that optional unowned should be used when the referencing object has a longer lifetime? I would expect there must be more...
You've misunderstood the release note and the meaning of the change in the language.
why Apple decided to make the unowned an optional type
They didn't. You can, and usually will, still say
unowned let owner : MyViewController
The only change here is that the unowned variable can be an Optional, which was illegal previously. This change takes care of an annoying edge case, that's all.
Above isn't true anymore
Yes, it is. Things are completely unchanged from before:
Weak references must be typed as Optional; they do not retain the object referred to, but they track the object referred to, and revert to nil if that object goes out of existence.
Unowned references do not retain the object referred to and do not track the object referred to, so it's up to you to prevent that object from going out of existence or you may end up with a dangling pointer and a crash.
The only thing that's changed is that there used to be an additional rule that an unowned reference type could not be an Optional. That rule is now gone.
As you rightly point out, if the unowned reference type is an Optional, this must be a var reference, not a let reference (because having this be an Optional would make no sense if you didn't have the power to change it from nil to an actual value and vice versa).
A typical use case is very much like what you yourself provided:
class Node {
unowned var parent: Node?
}
It seems reasonable to say that this Node may or may not have a parent (because it might be at the top of the graph), but that if it does have a parent, that parent should be unowned (a parent should retain its child, but a child should not retain its parent). Previously, the only way to say that was to make this a weak reference, which entails some unnecessary overhead, and is otiose, because we can absolutely guarantee that if a node has a parent, the parent will outlive the child. Now, you can say what you mean, which is generally a good thing.

Difference Between weak & unowned in respect to ARC memory management in Swift 3.1 [duplicate]

This question already has answers here:
What is the difference between a weak reference and an unowned reference?
(7 answers)
Swift. Is the (absolutely) sole specific advantage of unowned over weak, performance?
(4 answers)
Closed 5 years ago.
I am working on Swift and I have little bit confusion on usage of unowned and weak keywords for memory management in Swift.
Can any one help me to understand where to use unowned ?
Thanks in advance!
The most important difference is that unowned variables are very dangerous in Swift.
weak is an optional type, unowned is NOT.
This means that you can create code that uses weak as part of the logic. (think of asynchronous actions that take place only if a view controller is still being shown on the screen, when the code is ran, if the reference is "weak" it will fail silently without causing any other issues if the code is written correctly)
On the other hand, when a variable is unowned you are basically saying that this variable will always refer to something. And unlike weak, if you call it and there's nothing it will crash.
You generally never wanna use unowned. (I haven't come across any case where I had to). On the other hand, "weak self" variables are quite common when writing blocks.
You can see a good explanation on this question:
Shall we always use [unowned self] inside closure in Swift
EDIT: Actually, check the first and second most voted answers. They provide a clear explanation on WHEN to use unowned and how it works. The second even has pictures!
As per apple docs
There are some pretty good examples given on the developer website, check this link
As far as blocks are concerned as per Apple Docs:
Define a capture in a closure as an unowned reference when the closure
and the instance it captures will always refer to each other, and will
always be deallocated at the same time.
Conversely, define a capture as a weak reference when the captured
reference may become nil at some point in the future. Weak references
are always of an optional type, and automatically become nil when the
instance they reference is deallocated. This enables you to check for
their existence within the closure’s body.
To conclude Use a weak reference whenever it is valid for that
reference to become nil at some point during its lifetime. Conversely,
use an unowned reference when you know that the reference will never
be nil once it has been set during initialization.”

Meaning of exclamation mark in optional identifier in Swift? [duplicate]

This question already has answers here:
Why create "Implicitly Unwrapped Optionals", since that implies you know there's a value?
(10 answers)
Closed 7 years ago.
I know with exclamation mark I can unwrap an optional value, means I can convert optional type to a 'normal' type. But what about using exclamation in type identifier? I.e.
#IBOutlet weak var back: UIButton!
Why do I need !? Without ! it means back can not take a nil value, isn't it? As Int i means neither i can take a nil value. But then why I need ! in type identifier?
#IBOutlet types need to be optional, otherwise the compiler would complain that the
variables aren’t set in all initializers. Swift doesn’t “know” that Interface Builder is
supplying the views at run time; therefore it would do its job and raise a build error
about the unsupplied values.

Type and declaration restrictions on Swift capture specifiers

I'm confused about the type requirements and declaration restrictions for Swift capture specifiers. The documentation says that weak references must be var and "of optional type", and that unowned references must be of non-optional type. But Apple's own API reference has examples of unowned(unsafe) references declared as optionals, while the Xcode interface builder creates weak outlets and actions that are implicitly unwrapped (which is not always clearly "of optional type" in the language reference).
What types are required for each of the Swift capture specifiers? Which must be var and which can be let?
FWIW, I think its
weak can be Type? or Type!, but not Type; and must be var
unowned(safe) (same as unowned) must be Type; and may be let
unowned(unsafe) can be Type? or Type!; and may be let
but I'm far from sure.
First the Cocoaor Cocoa touch APIs are imported in swift fromobjective-c`. They are mapped in swift with best possible ways.So that both can interoperable.
Those unowned(unsafe) properties are marked as assign in ObjC. These are unsafe and ARC doesn't retain the object, and it doesn't make sure the reference gets reset to nil if the object is deallocated. These are old apple API and not changed with ARC and remain asassignbut you should makedelegateweak`
Do not look for headers for best practices in swift they have made many tricks to make swift and objective-c interoperable and if you do what headers do than you loose all safety swift proveide.
You are right
weak should be optional as contain nil automatically if objects get deallocate and no other pointer retain it
unowned(safe) should not be optional and will not reset to nilif objects deal-located
unowned(unsafe) can or can not be optional as it not provide any safety by ARC for object deal-location and do not reset to nil.You should not use this in swift program.Use unowned if needed.It is just for interoperability.
weak is always var because it can be changed when objects deallocate and set to nil.
unowned(safe) and unowned(unsafe) can be both var or let as they are dependent on you and run-time will not change these variables.
Note:You can not declare a unowned(unsafe) as optional in swift program.Its for just interoperability and should not be used in swift.They have made this because of assign or unretain properties can be nil