How to deal with weak in closure in Swift

Issue #326

Traditionally, from Swift 4.2 we need guard let self

1
2
3
4
5
6
7
8
9
addButton.didTouch = { [weak self] in
guard
let self = self,
let product = self.purchasedProduct()
else {
return

self.delegate?.productViewController(self, didAdd: product)
}

This is cumbersome, we can invent a higher order function to zip and unwrap the optionals

1
2
3
4
5
6
7
8
9
10
11
func with<A, B>(_ op1: A?, _ op2: B?, _ closure: (A, B) -> Void) {
if let value1 = op1, let value2 = op2 {
closure(value1, value2)
}
}

addButton.didTouch = { [weak self] in
with(self, self?.purchasedProduct()) {
$0.delegate?.productViewController($0, didAdd: $1)
}
}

Comments