Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Created January 12, 2021 17:43
Show Gist options
  • Save VAndrJ/1ea6344d7ed3f0f06438eafb9967a5c1 to your computer and use it in GitHub Desktop.
Save VAndrJ/1ea6344d7ed3f0f06438eafb9967a5c1 to your computer and use it in GitHub Desktop.
Reflections about Kotlin's scope functions in Swift
protocol Applyable {}
func with<T, R>(_ lhs: T, _ rhs: (T) throws -> R) rethrows -> R {
return try rhs(lhs)
}
extension Applyable where Self: AnyObject {
@discardableResult
func apply(_ block: (Self) throws -> Void) rethrows -> Self {
try block(self)
return self
}
func `let`<R>(_ block: (Self) throws -> R) rethrows -> R {
return try block(self)
}
}
extension Applyable where Self: Any {
func applied(_ block: (inout Self) throws -> Void) rethrows -> Self {
var mutableCopy = self
try block(&mutableCopy)
return mutableCopy
}
}
precedencegroup ForwardApplication {
associativity: left
higherThan: AssignmentPrecedence
}
precedencegroup ForwardComposition {
associativity: left
higherThan: ForwardApplication
}
infix operator |>: ForwardApplication
infix operator >>>: ForwardComposition
func |> <A, B>(a: A, f: (A) -> B) -> B { f(a) }
func >>> <A, B, C>(f: @escaping (A) -> B, g: @escaping (B) -> C) -> ((A) -> C) {{ a in g(f(a)) }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment