Strong and weak references in Swift

38,504

Solution 1

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

https://itunes.apple.com/tr/book/swift-programming-language/id881256329?mt=11

Solution 2

A var is strong by default. You can add the weak keyword before a var to make it weak.

Solution 3

Properties are strong by default, but if you want a weak property you can:

    weak var tenant: Person?

Source: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

Solution 4

This is more of an important comment, but I couldn't fit it in.

If you do

weak let name : SomeClass

It will give the following error:

'weak' must be a mutable variable, because it may change at runtime

You must do

weak var name : SomeClass

'weak' variable should have optional type 'SomeClass?'

So you must do:

weak var name : SomeClass?

Also, in Swift, all weak references are non-constant Optionals (think var vs. let) because the reference can and will be mutated to nil when there is no longer anything holding a strong reference to it. See here

As a result of this mandatory optional-ization, you always need to unwrap it so you can access its actual value.

Solution 5

Just wanted you to know that a var is strong by default but by adding "weak" in front of it you make it weak. In case you missed it

Share:
38,504

Related videos on Youtube

67cherries
Author by

67cherries

I've been programming for iOS for about four years. I've worked with objective-c, swift, python, java and javascript SO milestones: 6576th to the Strunk & White Badge :D

Updated on July 09, 2022

Comments

  • 67cherries
    67cherries almost 2 years

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

    @property(strong)...
    @property(weak)...
    

    How is this done in swift?

  • user102008
    user102008 over 9 years
    unowned does not translate to unsafe_unretained from Objective-C
  • mfaani
    mfaani over 6 years
    @ChrisPrince generally not recommended to do implicitly unwrapped optionals, but yes you can do that as well...
  • Chris Prince
    Chris Prince over 6 years
    We can chose to disagree on this point. And also take a look at IBOutlet member variables in Swift.