Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to deal with weak in closure in Swift #326

Open
onmyway133 opened this issue Jun 25, 2019 · 0 comments
Open

How to deal with weak in closure in Swift #326

onmyway133 opened this issue Jun 25, 2019 · 0 comments

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Jun 25, 2019

Traditionally, from Swift 4.2 we need guard let self

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

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)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant