Unreferenced (unowned)

When declaring a property or variable, prefix it with the unowned keyword to indicate that it is an unclaimed reference. An unclaimed reference cannot be set to nil because variables of non-optional types are not allowed to be assigned nil.

Two attributes, one of which is of optional type and one of which is not and refers to each other, are generally used to resolve circular strong references with an undirected reference.

case

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
    deinit { print("\(name) is being deinitialized")}}Copy the code
class CreditCard {
    let number: UInt64
    unowned let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit { print("Card #\(number) is being deinitialized")}}Copy the code

Note that the number attribute of the CreditCard class is defined as a UInt64 attribute, not an Int, to ensure that the number attribute has enough memory for a 16-bit card number on both 32-bit and 64-bit systems.

The following code snippet defines an optional Customer variable of type John to hold a reference to a particular Customer. Since it is an optional type, the variable is initialized to nil: var John: Customer?

Now you can create an instance of the Customer class, initialize the CreditCard instance with it, and assign the newly created CreditCard instance to the Customer’s card attribute:

john = Customer(name: "John Appleseed") john! .card = CreditCard(number: 1234_5678_9012_3456, customer: john!)Copy the code

After you associate two instances, their reference relationship looks like this:

The Customer instance holds a strong reference to the CreditCard instance, while the CreditCard instance holds an undirected reference to the Customer instance.

When you disconnect the strong reference held by the John variable, there is no strong reference to the customer instance:

Customer
CreditCard

John = nil // Print "John Appleseed is being deinitialized" // Print "Card"# 1234567890123456 is being deinitialized"
Copy the code

The final code shows that the constructors of both Customer and CreditCard instances print “destroy” after the John variable is set to nil.

Note that the example above shows how to use a secure undirected reference. Swift also provides unsecured, ownerless references for situations where run-time security checking needs to be disabled (for example, for performance reasons). As with all unsafe operations, it is your responsibility to review the code to make sure it is secure. You can declare an unsafe unattended reference via unowned(unsafe). If you try to access an unsafe reference to an instance after it has been destroyed, your program will try to access the memory address where the instance was before, which is an unsafe operation.

Source: http://www.piggybear.net/?p=681