How to deal with weak in closure in Swift

twitter logo github logo ・1 min read

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

twitter logo DISCUSS
Classic DEV Post from Feb 25

The Best Way to Advance Your Career

Where I answer a query from one of my awesome readers about how to advance your career based on my experience.

Khoa Pham profile image
My apps https://onmyway133.github.io/

DEV has become a critical resource for healthy software careers.

Create Your Account

100% free forever