DEV Community

Khoa Pham
Khoa Pham

Posted on

2 1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay