Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What good are unowned references?

Tags:

swift

Weak and Unowned references are used to prevent retain cycles in the situation where two objects each hold a reference to the other. I get the use of weak but I do not get the use of unowned. Here is Apple's example of a situation where one of the two objects should use an unowned reference:

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) { self.name = name }
}

class CreditCard {
     let number: UInt64
     unowned let customer: Customer
     init(number: UInt64, customer: Customer) {
         self.number = number
         self.customer = customer
     }
}

The idea is that a credit card cannot exist without a customer. Therefore a credit card can dispense with the optional unwrapping that the use of a weak reference would entail, and can instead use an unowned reference. Hmmm ... so why not use a strong reference? If all other references to the customer were to go away (which is not supposed to happen?) then the credit card's use of an owned reference would result in a crash; whereas its use of a strong reference would result in a memory leak. Huh? A choice between two evils? Better to crash because that is more likely to be noticed during development and testing?

Please help with some insight. Thanks.

like image 366
Verticon Avatar asked Dec 09 '16 13:12

Verticon


2 Answers

Better to crash because that is more likely to be noticed during development and testing?

Yes.

Well, not exactly.

The idea is that your app's design should ensure that no CreditCard instance outlives it's respective Customer instance. When you use unowned, you trust yourself to have a design in play that logically guarantees a crash-free execution.

Now, why would anyone ever use unowned over weak? Simple! unowned removes the whole hassle of Optional unwrapping, and if you know that your CreditCard instance will never outlive it's respective Customer instance, then you should use unowned by all means.

like image 174
Vatsal Manot Avatar answered Sep 28 '22 05:09

Vatsal Manot


unowned is actually much better than weak, in those situations where it is appropriate (i.e. it is certain that the unowned object will not go out of existence), because:

  • A weak reference must be an Optional, which may need unwrapping, and

  • A weak reference entails large amounts of overhead in order to track the reference and change it to nil if it is deallocated, whereas an unowned reference entails zero overhead.

like image 21
matt Avatar answered Sep 28 '22 06:09

matt