Wednesday, April 5, 2017 [Tweets] [Favorites]

Stop the weak-strong Swift Dance

Krzysztof Zabłocki (tweet):

The usual way of dealing with that is using either unowned or weak capture, wheres unowned requires almost no boilerplate, using weak usually requires this annoying dancing pattern:

obj.closure = { [weak self, weak other] some, arguments in 
    guard let strongSelf = self else { return }
    /// ... code
}

I find this ugly, lets instead create strongify function and turn all those calls into something like:

obj.closure = strongify(self, other) { instance, other, some, arguments in
    /// ... code
}

[…]

Basically we generate a variant that takes N context arguments and N original function arguments and strongify them. A little boilerplate to remove a lot of boilerplate from your call-sites.

Some are suggesting that a name like withWeak() would make more sense.

Previously: @weakify and @strongify Macros.

2 Comments

I have a library that does something like this, though it's named `weakify` and has a slightly different purpose: https://github.com/klundberg/weakify.git

I'd much rather spend my time on app functionality than faffing about with this bullshit.

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment