Last active
November 4, 2021 13:34
Generic replacement for assigning values with self-executing closures
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
/// 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() | |
} |
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
You could use this instead of: