# Weak closure reference

**URL:** <https://forums.swift.org/t/weak-closure-reference/16085>\
**Category:** Discussion\
**Created:** [September 11, 2018, 9:05pm UTC](https://forums.swift.org/t/weak-closure-reference/16085 "2018-09-11T21:05:00Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vyacheslav](https://avatars.discourse-cdn.com/v4/letter/v/b9e5f3/32.png) [@Vyacheslav](https://forums.swift.org/u/Vyacheslav)\
**Post date:** [September 11, 2018, 9:05pm UTC](https://forums.swift.org/t/weak-closure-reference/16085/1 "2018-09-11T21:05:00Z")

</div>

I requested a new feature

Implement `weak var callback: (() -> ())?`

What does the community think about this?

> <https://github.com/apple/swift/issues/50737>
>
> | | |
> |------------------|-----------------|…
> |Previous ID | SR-8205 |
> |Radar | None |
> |Original Reporter | trololo (JIRA User) |
> |Type | New Feature |
> 
> \<details\>
> \<summary\>Additional Detail from JIRA\</summary\>
> 
> | | |
> |------------------|-----------------|
> |Votes | 0 |
> |Component/s | Compiler |
> |Labels | New Feature |
> |Assignee | None |
> |Priority | Medium |
> 
>    
> 
> md5: e479016a2ea10381e01cb7c76fea9cbc
> 
> \</details\>
> 
> 
> 
> 
> 
> \*\*Issue Description:\*\*
> 
> 
> It seems that this code leads to a retain cycle.
> 
>  
> 
> class Container {
> 
> var callback: (() -\\\> ())?
> 
> func some() { }
> 
> init() { }
> 
> deinit {
> 
> print("deinit() Container")
> 
> }
> 
> }
> 
>  
> 
> var container: Container? = Container()
> 
> container?.callback = container?.some 
> 
> container = nil
> 
> no "deinit() Container" as output message.
> 
> in this case \\\`weak var callback: (() -\\\> ())?\\\` would be very useful.

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [September 11, 2018, 9:39pm UTC](https://forums.swift.org/t/weak-closure-reference/16085/2 "2018-09-11T21:39:32Z")

</div>

What would the semantics be?

---

<div class="post-metadata">

**Author:** ![anandabits](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anandabits/32/355_2.png) [@anandabits](https://forums.swift.org/u/anandabits)\
**Post date:** [September 11, 2018, 9:42pm UTC](https://forums.swift.org/t/weak-closure-reference/16085/3 "2018-09-11T21:42:29Z")

</div>

This topic has come up before in one of the discussions lined to here: [Guarded closures](https://forums.swift.org/t/guarded-closures/11029). You may find those threads worth reading for background on the topic.

---

<div class="post-metadata">

**Author:** ![davbeck](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davbeck/32/32237_2.png) [@davbeck](https://forums.swift.org/u/davbeck)\
**Post date:** [September 12, 2018, 5:07am UTC](https://forums.swift.org/t/weak-closure-reference/16085/4 "2018-09-12T05:07:34Z")

</div>

I agree. On a related note, I think structs (and protocols that could be structs) should be allowed to be weak too since they may contain reference counted objects. Why should I have to make my delegate protocol require a class implementation just so I can mark it as weak in case it is?

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [September 12, 2018, 5:09am UTC](https://forums.swift.org/t/weak-closure-reference/16085/5 "2018-09-12T05:09:04Z")

</div>

> [@davbeck](#):
>
> I agree. On a related note, I think structs (and protocols that could be structs) should be allowed to be weak too since they may contain reference counted objects

What would it mean to have a weak struct though? When would the weak "reference" become nil?

---

<div class="post-metadata">

**Author:** ![davbeck](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davbeck/32/32237_2.png) [@davbeck](https://forums.swift.org/u/davbeck)\
**Post date:** [September 12, 2018, 5:10am UTC](https://forums.swift.org/t/weak-closure-reference/16085/6 "2018-09-12T05:10:54Z")

</div>

Assuming it has plain contents, nothing. It would effectively be a no-op. But in the case that it has object properties, each of those would be weakly referenced instead of strongly.

---

<div class="post-metadata">

**Author:** ![AlexanderM](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexanderm/32/9781_2.png) [@AlexanderM](https://forums.swift.org/u/AlexanderM)\
**Post date:** [September 12, 2018, 5:13am UTC](https://forums.swift.org/t/weak-closure-reference/16085/7 "2018-09-12T05:13:11Z")

</div>

Yet another problem that would so simply be solved if `weak` was just a `Weak<T>` struct, but people keep shitting on that idea whenever I see it brought up, lol.

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [September 12, 2018, 5:15am UTC](https://forums.swift.org/t/weak-closure-reference/16085/8 "2018-09-12T05:15:57Z")

</div>

> [@AlexanderM](#):
>
> Yet another problem that would so simply be solved if `weak` was just a `Weak<T>` struct, but people keep shitting on that idea whenever I see it brought up, lol.

I'm not sure what problem that would solve. It looks like a change to the spelling that would be trivial to implement but not really have a semantic effect.

---

<div class="post-metadata">

**Author:** ![Slava\_Pestov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/slava_pestov/32/30204_2.png) [@Slava\_Pestov](https://forums.swift.org/u/Slava_Pestov)\
**Post date:** [September 12, 2018, 5:18am UTC](https://forums.swift.org/t/weak-closure-reference/16085/9 "2018-09-12T05:18:22Z")

</div>

> [@davbeck](#):
>
> Assuming it has plain contents, nothing. It would effectively be a no-op. But in the case that it has object properties, each of those would be weakly referenced instead of strongly.

`Array<T>` is a struct. Would this that a `weak Array<T>?` would become nil if the strong reference count of any element of the array dropped to 0? What if the element type `T` is itself a struct?

---

<div class="post-metadata">

**Author:** ![Daniel\_Resnick](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/daniel_resnick/32/480_2.png) [@Daniel\_Resnick](https://forums.swift.org/u/Daniel_Resnick)\
**Post date:** [September 12, 2018, 5:19am UTC](https://forums.swift.org/t/weak-closure-reference/16085/10 "2018-09-12T05:19:00Z")

</div>

I agree. I think something that would solve that particular problem would be something like `Box<T>` that purely is an object wrapper for a value type `T` and conforms to all protocols that `T` conforms to by delegating to it.

---

<div class="post-metadata">

**Author:** ![AlexanderM](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexanderm/32/9781_2.png) [@AlexanderM](https://forums.swift.org/u/AlexanderM)\
**Post date:** [September 12, 2018, 5:37am UTC](https://forums.swift.org/t/weak-closure-reference/16085/11 "2018-09-12T05:37:13Z")

</div>

Oops, I'm really tired and I was very unclear. Let me try again.

`weak` as a language attribute is given a lot of special treatment that it just doesn't need. The ability to make weak closure is yet another undeserved special case. The other being the lack of ability to make weak types nested within other types.

---

<div class="post-metadata">

**Author:** ![Panajev](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/panajev/32/1227_2.png) [@Panajev](https://forums.swift.org/u/Panajev)\
**Post date:** [September 12, 2018, 7:34am UTC](https://forums.swift.org/t/weak-closure-reference/16085/12 "2018-09-12T07:34:31Z")

</div>

What would it mean if the storage type of a strict variable were weak though? Strings are value types and the weak/strong modifier is reference counting territory really.

---

<div class="post-metadata">

**Author:** ![Vyacheslav](https://avatars.discourse-cdn.com/v4/letter/v/b9e5f3/32.png) [@Vyacheslav](https://forums.swift.org/u/Vyacheslav)\
**Post date:** [September 12, 2018, 8:51am UTC](https://forums.swift.org/t/weak-closure-reference/16085/13 "2018-09-12T08:51:35Z")

</div>

Closure is a reference type.  
I'm not sure what does namely 'semantics' mean.  
But in my example

```
class Container {

    weak var callback: (() -> ())? // this line

    func some() { }

    init() { }

    deinit {

        print("deinit() Container")

    }

}

var container: Container? = Container()

container?.callback = container?.some 

container = nil

```

should help to resolve the retain cycle.

It is possible to use nil closure. I don't understand why this was not implemented.

Closures are reference types.

[https://docs.swift.org/swift-book/LanguageGuide/Closures.html](https://docs.swift.org/swift-book/LanguageGuide/Closures.html)

`weak` , imho, have to be implemented.

---

<div class="post-metadata">

**Author:** ![DevAndArtist](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/devandartist/32/287_2.png) [@DevAndArtist](https://forums.swift.org/u/DevAndArtist)\
**Post date:** [September 12, 2018, 9:57am UTC](https://forums.swift.org/t/weak-closure-reference/16085/14 "2018-09-12T09:57:36Z")

</div>

It's not the value that should be weak but the captured refences. If any of the reference becomes unavailable, the whole optional will invalidate and return `nil`. You may also want `unowned` closures where you known what you're doing.

I pitched this once myself: [[Pitch] Introduction of `weak/unowned` closures](https://forums.swift.org/t/pitch-introduction-of-weak-unowned-closures/6095)

---

<div class="post-metadata">

**Author:** ![Vyacheslav](https://avatars.discourse-cdn.com/v4/letter/v/b9e5f3/32.png) [@Vyacheslav](https://forums.swift.org/u/Vyacheslav)\
**Post date:** [September 12, 2018, 10:11am UTC](https://forums.swift.org/t/weak-closure-reference/16085/15 "2018-09-12T10:11:30Z")

</div>

guarded closures, imho, contain difficult context and restrictions to understand.

---

<div class="post-metadata">

**Author:** ![davbeck](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/davbeck/32/32237_2.png) [@davbeck](https://forums.swift.org/u/davbeck)\
**Post date:** [September 12, 2018, 2:46pm UTC](https://forums.swift.org/t/weak-closure-reference/16085/16 "2018-09-12T14:46:51Z")

</div>

If I understand how Array is implemented, it would effect the reference count of the underlying storage class, not the individual elements. So if I have a reference to `a` and a weak reference to `[a]`, the array would immediately be released because there are no other references to the storage.

That being said, Array (and other collections) are a good example of the problems this would introduce. Many users would think that `weak var foo: Array<T>?` would weakly reference the elements instead of the array itself.

The biggest area I find myself wanting this is with delegates. For instance:

```swift
protocol FooDelegate {}

class Foo {
    weak var delegate: FooDelegate?
}

```

That won't compile because in this case, `FooDelegate` could be a struct. But as `Foo` I don't really care what implements my delegate protocol, I just don't want to create a retain cycle if it's a class that might reference me. But for that matter, I wouldn't want a struct that references me to retain me either. So you have to restrict `FooDelegate` to be a class or risk a retain cycle.

---

<div class="post-metadata">

**Author:** ![QuinceyMorris](https://avatars.discourse-cdn.com/v4/letter/q/d26b3c/32.png) [@QuinceyMorris](https://forums.swift.org/u/QuinceyMorris)\
**Post date:** [September 13, 2018, 12:34am UTC](https://forums.swift.org/t/weak-closure-reference/16085/17 "2018-09-13T00:34:20Z")

</div>

> [@Vyacheslav](#):
>
> Implement `weak var callback: (() -> ())?`

The problem with this is that it's effectively unusable.

A `weak` variable is incapable of keeping the referenced object alive. Therefore, in order for such a variable to be non-nil **_ever_** , there must be an owning variable **_somewhere else_**.

But that's just not how closures are typically used. A stored callback is typically set from a passed parameter that comes from a closure literal (`{ … }`), which is stored strongly **_nowhere else_**.

A delegate property is typically a different scenario. Typically, an object A sets **_itself_** as a delegate of an object B, and stores an owning reference to object B, which means B's `weak var delegate: …` property is non-nil for as long as A is alive.

Or, if object A creates a new object C to set as the delegate of object B, then A is responsible for keeping C alive.

But this isn't a thing for closures. Object A typically has no reason to store an owning reference to a closure that it passes to B (or sets as a property of B).

---

<div class="post-metadata">

**Author:** ![Vyacheslav](https://avatars.discourse-cdn.com/v4/letter/v/b9e5f3/32.png) [@Vyacheslav](https://forums.swift.org/u/Vyacheslav)\
**Post date:** [September 13, 2018, 6:14am UTC](https://forums.swift.org/t/weak-closure-reference/16085/18 "2018-09-13T06:14:35Z")

</div>

Weak closures have to be used when you try to use a function as a closure. When you feed a function of a current class into another class function with, for instance, completion handler result the only choice is to use inside the second class weak closure to prevent reference cycle.

---

<div class="post-metadata">

**Author:** ![QuinceyMorris](https://avatars.discourse-cdn.com/v4/letter/q/d26b3c/32.png) [@QuinceyMorris](https://forums.swift.org/u/QuinceyMorris)\
**Post date:** [September 13, 2018, 6:00pm UTC](https://forums.swift.org/t/weak-closure-reference/16085/19 "2018-09-13T18:00:27Z")

</div>

> [@Vyacheslav](#):
>
> Closure is a reference type.

My point was that storing **_a weak reference to the closure_** doesn't help.

What is need in the case you describe is a strong reference to a closure that captures `self` weakly. In a different context, I suggested new syntax along this line:

```swift
    self.callback = [weak self in] self.someMethod

```

However, once the closure that captures `self` strongly is created, you can't retrospectively make the `self` capture weak.

---

<div class="post-metadata">

**Author:** ![Vyacheslav](https://avatars.discourse-cdn.com/v4/letter/v/b9e5f3/32.png) [@Vyacheslav](https://forums.swift.org/u/Vyacheslav)\
**Post date:** [September 13, 2018, 9:13pm UTC](https://forums.swift.org/t/weak-closure-reference/16085/20 "2018-09-13T21:13:53Z")

</div>

It doesn't help when you save function as a closure.

Please, understand, capturing using [some\_to\_do] is another context.

[Next page](https://forums.swift.org/t/weak-closure-reference/16085.md?page=2)
