#59: Using unowned Safely in Swift

unowned is like a non-optional weak reference: it does not increase the retain count, but Swift assumes the referenced object will still exist when accessed.

final class Customer {
    let name: String
    var card: CreditCard?

    init(name: String) { self.name = name }
}

final class CreditCard {
    unowned let customer: Customer

    init(customer: Customer) {
        self.customer = customer
    }
}

This is safe only when the lifetime relationship is guaranteed by design.

If the reference could become nil, use weak instead. unowned is convenient, but the penalty for being wrong is a crash.


I'm also on Twitter and GitHub.

Subscribe via RSS.