DEV Community

Khoa Pham
Khoa Pham

Posted on

How to deal with weak in closure in Swift

Traditionally we need to if let to strongSelf

addButton.didTouch = { [weak self] in
    guard
        let strongSelf = self,
        let product = strongSelf.purchasedProduct()
    else {
        return

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

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

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?.addProductController($0, didIncrease: $1)
    }
}

Original post https://github.com/onmyway133/blog/issues/326

Top comments (0)