# Weak reference doesn't work as expected when passing it to a function's argument

**URL:** <https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432>\
**Category:** Using Swift\
**Tags:** swiftui, weak, retain-cycle\
**Created:** [April 16, 2023, 3:32pm UTC](https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432 "2023-04-16T15:32:33Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![vigdora](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vigdora/32/34512_2.png) [@vigdora](https://forums.swift.org/u/vigdora)\
**Post date:** [April 16, 2023, 3:32pm UTC](https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432/1 "2023-04-16T15:32:33Z")

</div>

I am already aware of the strong/weak reference concept in swift.  
yet after running the next code, and tapping on the Button (and dismissing the screen), the TestViewModel stayed in memory!  
I was expecting that using [weak viewmodel] will be enough to prevent it.  
in the second example I managed to fix it - but I don't understand why it worked

```swift
import SwiftUI
import Resolver

struct TestScreen: View {
    
    @StateObject var viewmodel = TestViewModel()
    @Injected var testStruct: TestStruct
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
            
            VStack(spacing: 0) {
                
                Button("go back") { [weak viewmodel] in
                        testStruct.saveActionGlobaly(onAsyncAction: viewmodel?.someAsyncAction )
                        presentationMode.wrappedValue.dismiss()
                    }
            }
        }
    }
}

```

```swift

import Foundation
import Resolver
import SwiftUI

public class TestStruct {
   var onAsyncAction: (() async throws -> Void)?
    
    public func saveActionGlobaly(onAsyncAction: (() async throws -> Void)?) {
        self.onAsyncAction = onAsyncAction
    } 
}

```

EXAMPLE 2:  
I managed to prevent the leak by changing the code this way:  
(notice the changes in the callback passed to onAsyncAction)

```plaintext
import Resolver

struct TestScreen: View {
    
    @StateObject var viewmodel = TestViewModel()
    @Injected var testStruct: TestStruct
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
            
            VStack(spacing: 0) {
                
                Button("go back") { [weak viewmodel] in
                        testStruct.saveActionGlobaly(onAsyncAction: { await viewmodel?.someAsyncAction() } )
                        presentationMode.wrappedValue.dismiss()
                    }
            }
        }
    }
}

```

I dont understand why the second TestScreen managed to apply the weak reference and the first one didn't,  
thanks (:

environment:  
swift 5  
xcode 14.2

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [April 16, 2023, 4:07pm UTC](https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432/2 "2023-04-16T16:07:12Z")

</div>

This is a good question about how weak references interact with bound method references! The first thing to note is that when you form a bound reference to some instance method, you are implicitly creating a closure which captures the `self` param for the method. So in the following code:

```swift
class C {
  var x: Int = 0
  func f() { print(x) }
}

let c = C()
c.x = 3
let printX = c.f
printX() // 3

```

the line `let printX = c.f` is doing basically the same thing as if you had written:

```swift
let printX = { [c] in
  c.f()
}

```

If you think about what would happen after `c` goes out of scope, you can see why this has to be the case: `printX` is able to be passed around independently of `c`, and if it didn't have its own (strong) reference to the underlying instance, it would be possible for `c` to be released and deallocated out from underneath `printX`, which would suddenly present a memory safety issue (because `printX` purports to call the `C.f` method on an instance that no longer exists.

But why does this still happen in the `TestViewModel` case when we have a _weak_ reference? The thing to notice here is that while we may have a weak reference _externally_, within `TestViewModel` all methods work with a _strong_ reference to `self`. That is, for the duration of the execution of the method, it is not possible for `self` to disappear out from under us—it will only be possible for `self` to be deallocated after the method completes execution and the `self` parameter is released.

So in the case of a bound method _reference_, if we're able to form a reference to `TestViewModel.someAsyncAction` that can be invoked later, we must have a _strong_ reference to `TestViewModel` to pass as the `self` parameter. By forming that method reference through our weak instance reference, we are attempting to form the strong reference _at the time we form the `onAsyncAction` closure_. The code you've written in the first example is roughly semantically equivalent to the following:

```swift
let onAsyncAction = if let viewModel = viewModel {
  viewModel.someAsyncAction
} else {
  nil
}
testStruct.saveActionGlobally(onAsyncAction: onAsyncAction)

```

By doing things this way, we have formed a function which captures a strong reference to the `TestViewModel` instance _for the duration of the lifetime of the underlying function_, so we cannot deallocate `viewModel` until after `onAsyncAction` is deallocated.

OTOH, in the second example, we are forming a closure which captures only captures a _weak_ reference to `TestViewModel`. Yes, we still have to form a strong reference in order to _invoke_ `someAsyncAction`, but the key here is that this strong reference is formed only at the time of _execution_ of `onAsyncAction`, and only for the _duration_ of execution of `someAsyncAction`. The more explicit semantic equivalent looks something like this:

```swift
testStruct.saveActionGlobaly(onAsyncAction: {
  if let viewModel = viewModel {
    viewModel.someAsyncAction()
  }
})

```

Hopefully this version makes it a bit clearer that we are only forming the strong reference to `TestViewModel` _within_ the closure passed to `saveActionGlobally`, and that this reference gets released once we exit the scope, allowing the `TestViewModel` instance to be released if there are only weak references remaining.

---

<div class="post-metadata">

**Author:** ![vigdora](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vigdora/32/34512_2.png) [@vigdora](https://forums.swift.org/u/vigdora)\
**Post date:** [April 17, 2023, 3:47pm UTC](https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432/3 "2023-04-17T15:47:19Z")

</div>

Thank you so much for a very descriptive answer!  
I think your example, `where c can be deallocated out from underneath printX` - was very good.

before your answered I actually tried to explained it to my self by adding the compiler into the equation.  
I am curious to know if you find the next explanation legit as well?

first of all, the weak-reference concept is a compiler game - meaning, the complier runs over the first example and translate it to:

```swift
let onAsyncAction = if let viewModel = viewModel {
  viewModel.someAsyncAction
} else {
  nil
}
testStruct.saveActionGlobally(onAsyncAction: onAsyncAction)

```

so, there is another step where the compiler translate `onAsyncAction` to be a closure like so (very abstract):

```swift
let onAsyncAction = { [viewmodel] in
  viewmodel.someAsyncAction()
}

```

and hands it over to `onAsyncAction` argument.  
in other words, the returned closure from evaluating `onAsyncAction` is holding another implicit viewmodel reference. the compiler can't conclude the explicit and the implicit viewmodels are related, thus the weakness is not applied to the later

to conclude:  
my explanation here implies that it is more a compiler issue rather than a pre-meditated design - or at least it could be solved somehow at this stage if swift developers wanted too

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [April 17, 2023, 4:14pm UTC](https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432/4 "2023-04-17T16:14:28Z")

</div>

> [@vigdora](#):
>
> I am curious to know if you find the next explanation legit as well?

I think this explanation mostly makes sense, but there's a couple things that it misses:

> [@vigdora](#):
>
> first of all, the weak-reference concept is a compiler game - meaning, the complier runs over the first example and translate it to:

What you've illustrated here is not at all specific to weak references—this 'compiler game' is simply the fully-explicit version of the optional chaining operator `?.` and applies to _any_ optional. If `x` has type `Optional<T>` for some type `T` then `let z = x?.y` evaluates

```swift
let z = if let x = x { x.y } else { nil }

```

The only thing here specific to weak references is that the conditions where a weak reference will evaluate to `nil` are different than for a non-weak variable of optional type.

> [@vigdora](#):
>
> so, there is another step where the compiler translate `onAsyncAction` to be a closure like so (very abstract):

while this transformation is basically correct, I think it's more accurate to think about this transformation being applied _at the point where you form the bound method reference_. That is, rather than thinking about it being something applied to `onAsyncAction`, you should think about the 'full' version of the transformation applied to `let onAsyncAction = viewModel?.someAsyncAction` as looking like:

```swift
let onAsyncAction = if let viewModel = viewModel {
  { [viewModel] in viewModel.someAsyncAction() }
} else {
  nil
}

```

> [@vigdora](#):
>
> the compiler can't conclude the explicit and the implicit viewmodels are related, thus the weakness is not applied to the later

I wouldn't think about this as so much that the compiler _can't_ figure this out, but that it is at odds with how the compiler chooses to model weak references. Specifically, `weak` is something that applies to a particular _declaration_, and copying from a weak variable to a non-weak variable involves attempting to form a strong reference to the underlying instance. That is, in the transformed code above, when you have `if let viewModel = viewModel`, that expresses the action of "check if the instance referred to by `viewModel` still exists and if so form a new (strong) reference to it called `viewModel`."

When you perform this action _outside_ the closure, you're saying "check if `viewModel` exists and if so form a strong function reference to the bound `someAsyncAction` method (which captures `viewModel` strongly) and store it in `onAsyncAction`" but when you perform this _inside_ the closure you are saying "when `onAsyncAction` is executed, check if `viewModel` exists and if so form a strong reference to call the `someAsyncAction` method, then release the strong reference afterwards."

---

<div class="post-metadata">

**Author:** ![vigdora](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vigdora/32/34512_2.png) [@vigdora](https://forums.swift.org/u/vigdora)\
**Post date:** [April 18, 2023, 7:39am UTC](https://forums.swift.org/t/weak-reference-doesnt-work-as-expected-when-passing-it-to-a-functions-argument/64432/5 "2023-04-18T07:39:38Z")

</div>

I agree - thank you so much!
