Last active
February 4, 2020 03:43
-
-
Save dfrobison/0ef1f9ee3abd66ab9206b1b8572e24a3 to your computer and use it in GitHub Desktop.
[First Class Functions] From John Sundell (https://www.swiftbysundell.com/articles/first-class-functions-in-swift/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Introducing a 'combine' function for applying a value to | |
// any function or closure: | |
func combine<A, B>( | |
_ value: A, | |
with closure: @escaping (A) -> B | |
) -> () -> B { | |
return { closure(value) } | |
} | |
// Example | |
// A view controller that currently captures 'self' weakly, in | |
// order to call a method on a 'productManager' property object: | |
class ProductViewController: UIViewController { | |
... | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
buyButton.handler = { [weak self] in | |
guard let self = self else { | |
return | |
} | |
self.productManager.startCheckout(for: self.product) | |
} | |
} | |
} | |
// Using our new combine function: | |
class ProductViewController: UIViewController { | |
... | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
buyButton.handler = combine(product, | |
with: productManager.startCheckout | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment