Last active
July 27, 2022 17:52
-
-
Save wotjd/7acd1bcaa1598e6b997986dca605d5e9 to your computer and use it in GitHub Desktop.
inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
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
// poor arrow function expression implementation like javascript's using infix operator and closure | |
precedencegroup ArrowFunctionExpressionPrecedence { | |
associativity: left | |
higherThan: BitwiseShiftPrecedence | |
} | |
infix operator =>: ArrowFunctionExpressionPrecedence | |
infix operator ==>: ArrowFunctionExpressionPrecedence | |
func =><T, U>(lhs: T, rhs: (T) -> U) -> U { | |
rhs(lhs) | |
} | |
func =><T: AnyObject>(lhs: T, rhs: (T) -> Void) -> T { | |
rhs(lhs) | |
return lhs | |
} | |
// to avoid "ambiguous use of operator" error | |
func ==><T>(lhs: T, rhs: (inout T) -> Void) -> T { | |
var t = lhs | |
rhs(&t) | |
return t | |
} | |
// usage | |
2 => { $0 / 2 } => { $0 + 1 } // 2 | |
let value = 1 ==> { $0 += 2 } // 3 | |
// configure instance right after initialization | |
let label = UILabel() => { $0.text = "hello" } | |
label.text // hello | |
// keyPath | |
let materials = [ | |
"Hydrogen", | |
"Helium", | |
"Lithium", | |
"Beryllium" | |
] | |
materials.map { $0 => \.count } | |
// is equivalent to | |
materials.map(\.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment