Last active
March 28, 2019 16:21
-
-
Save mkj-is/5deae6c24cbce62f813a30c7163835a0 to your computer and use it in GitHub Desktop.
Lift/const operator 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
/// 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