Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Last active January 24, 2017 16:52
Show Gist options
  • Save Ben-G/ef66f8edd653095ee3b9b78b161bed3c to your computer and use it in GitHub Desktop.
Save Ben-G/ef66f8edd653095ee3b9b78b161bed3c to your computer and use it in GitHub Desktop.
Function that lifts a function with non-optional input to one with optional input.
// Thanks to @jckarter for pointing that this is just Optional's map implementation...
{ $0.map(f) }
/// Takes a function with non-optional input and non-optional return and lifts it to a function
/// with optional input and optional return.
/// The lifted function will return `nil` iff the input is `nil`, otherwise the input will be
/// applied to the original function which will return a non-`nil` value.
public func liftToOptional<T,U>(_ f: @escaping (T) -> U) -> (T?) -> U? {
return { arg in
guard let arg = arg else { return nil }
return f(arg)
}
}
// Example: Allows to lift (String) -> UIView, to (String?) -> UIView?
// When working directly with optionals, the above can be resolved with by using `flatMap`.
// But if optionals are in another container (e.g. an Observable), this function seems necessary.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment