Skip to content

Instantly share code, notes, and snippets.

@mkj-is
Last active March 28, 2019 16:21
Show Gist options
  • Save mkj-is/5deae6c24cbce62f813a30c7163835a0 to your computer and use it in GitHub Desktop.
Save mkj-is/5deae6c24cbce62f813a30c7163835a0 to your computer and use it in GitHub Desktop.
Lift/const operator in Swift
/// Lift operator (instance to function, function to function with one more parameter, key-path to function)
/// This operator is similar to `const` function from Haskell.
prefix operator ^
/// Lift instance to function returning constant result.
@inline(__always)
prefix func ^ <T>(instance: @autoclosure @escaping () -> T) -> () -> T {
return instance
}
/// Lift function with no parameters to function with one parameter,
/// which will be thrown-away.
@inline(__always)
prefix func ^ <P, R>(function: @escaping () -> R) -> (P) -> R {
return { _ in
function()
}
}
/// Lift key-path to function receiving instance and returning property value.
@inline(__always)
prefix func ^ <T, P>(keyPath: KeyPath<T, P>) -> (T) -> P {
return { $0[keyPath: keyPath] }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment