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)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git