Skip to content

Instantly share code, notes, and snippets.

@PimCoumans
Last active November 4, 2021 13:34
Show Gist options
  • Save PimCoumans/93f95f175161c104eede34b39b1ea387 to your computer and use it in GitHub Desktop.
Save PimCoumans/93f95f175161c104eede34b39b1ea387 to your computer and use it in GitHub Desktop.
Generic replacement for assigning values with self-executing closures
/// Executes a closure and returns resulting generic value
/// Idea to replace 'executing closure pattern' used to assign values with some logic.
/// Example:
/// ```
/// let image: UIImage? = make {
/// if #available(iOS 13.0, *) {
/// return UIImage(systemName: "plus.square.fill.on.square.fill")
/// }
/// return UIImage(named: "fallbackImage")
/// }
/// ```
/// - Parameter maker: Closure that is immediately executed to return value
/// - Returns: Result of executing closure
func make<T>(maker: () -> T?) -> T? {
return maker()
}
@PimCoumans
Copy link
Author

So, you'd do something like this:

let image: UIImage? = make {
	if #available(iOS 13.0, *) {
		return UIImage(systemName: "plus.square.fill.on.square.fill")
	}
	return UIImage(named: “fallbackImage")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment