简体   繁体   中英

Swift: Unowned references

The swift documentation says

unowned references are defined using non-optional types.

But we can define an unowned variable as optional. It doesn't seem like a hard requirement for an unowned to be non-optional.

What is difference between weak optional & unowned optional..?

 class Person {

        let name: String
        var apartment: Apartment?

        init(name: String) {
            self.name = name
            print("\(name) is being initialized")
        }
        deinit {
            print("\(name) is being deinitialized")
        }
    }


    class Apartment {
        let unit: String
        init(unit: String) { self.unit = unit }
        unowned var tenant: Person?
        deinit { print("Apartment \(unit) is being deinitialized") }
    }

Neither weak nor unowned increase the reference count of an object; That is they will not prevent an object from being released if there are no remaining strong references.

The main difference between weak and unowned is what happens when the referred-to object is released; a weak reference becomes nil while an unowned reference still holds a (now invalid) reference to the object, so your program will crash if you try and access it.

Using an optional for an weak reference is required, since it can become nil . Using an optional for an unowned reference is syntactically possible, but the semantics aren't sensible. From the Swift Programming language book:

...an unowned reference is used when the other instance has the same lifetime or a longer lifetime

Given this definition, there is no point at which the unowned property should be nil . You can see this from your example; Clearly it is possible for an apartment to be without a tenant and a person who is currently a tenant can cease to exist; If you use unowned with an optional tenant you will be left with an invalid tenant reference.

Consider the difference between this and the credit-card example given in the book:

The relationship between Customer and CreditCard is slightly different from the relationship between Apartment and Person seen in the weak reference example above. In this data model, a customer may or may not have a credit card, but a credit card will always be associated with a customer. A CreditCard instance never outlives the Customer that it refers to. To represent this, the Customer class has an optional card property, but the CreditCard class has an unowned (and non-optional) customer property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM