Shortcut closure syntax in case of [weak self]

Viewed 57

Let's call some function, which has an escaping closure as a parameter:

someFunc(complition: {
    self.someAnotherFunc()
})

is equivalent to:

someFunc(complition: { [self] in
    someAnotherFunc()
})

is equivalent to:

someFunc(someAnotherFunc)

Was that correct?
I think that was correct.
self is capturing strongly above.

And what about case of [weak self]?
Is the only way we can write?:

someFunc(complition: { [weak self] in
    self?.someAnotherFunc()
})

Can't we somehow to write it like someFunc(someAnotherFunc)?

P.S. Okey, there is one more way to write it, I know:

someFunc { [weak self] in
    self?.someAnotherFunc()
}

But what about even more concise form?

1 Answers

Currently (Swift 5.4) Nothing else

Actually, the default behavior of closures is to NOT capture self at all. But as soon as you reference self inside, it will create a strong reference to it.

There is an open discussion about it here on swift.org

Since you did not mention the code of your function, I can't be sure about your needs but generally, you may face some situations where you can ignore the self capture:

  1. When you need a non-escaping closure
  2. When the parent function is a class function (like the UIView.animate...)
Related