Dealing With Weak in Closure-based Delegation
Oleg Dreyman (via Joshua Emmons):
Let’s look at the core of the problem: 99% of the time, when assigning a delegation callback, there should be a
[weak self]
capture list, but nothing is actually preventing ourselves from omitting it. No errors, no warnings, nothing. What if instead we could force the correct behavior?[…]
Leveraging the power of Swift generics, we can do better:
struct DelegatedCall<Input> { private(set) var callback: ((Input) -> Void)? mutating func delegate<Object : AnyObject>(to object: Object, with callback: @escaping (Object, Input) -> Void) { self.callback = { [weak object] input in guard let object = object else { return } callback(object, input) } } }
2 Comments RSS · Twitter
@Ben His way is definitely less clean. The question is whether it’s worth it to prevent errors.
Dreyman's general thesis is solid:
However, I disagree with his taste that this kind of declaration
is more developer-friendly than the original
Despite my distaste for Swift's disorganized “junk after the opening brace” closure syntax, the capture list still seems a bit cleaner compared to the extra method call and shadowing of `self` as an additional parameter.