68cherries 68cherries - 1 year ago 115
Swift Question

Strong and weak references in Swift

In Objective C you can define a property as having a strong or weak reference like so:


How is this done in swift?

Answer Source

Straight from the Swift Language guide:

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { println("\(name) is being deinitialized") }

class Apartment {
    let number: Int
    init(number: Int) { self.number = number }
    weak var tenant: Person?
    deinit { println("Apartment #\(number) is being deinitialized") }

properties are strong by default. But look at the tenant property of the class "Apartment", it is declared as weak. You can also use the unowned keyword, which translates to unsafe_unretained from Objective-C


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download