Skip to content

Instantly share code, notes, and snippets.

@wotjd
Last active July 27, 2022 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wotjd/7acd1bcaa1598e6b997986dca605d5e9 to your computer and use it in GitHub Desktop.
Save wotjd/7acd1bcaa1598e6b997986dca605d5e9 to your computer and use it in GitHub Desktop.
// 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