Is it possible to write a generic apply(block:) method? (like ruby yield_self)

You can't really extend Any, but I often define this function:

infix operator |>   { precedence 50 associativity left }
public func |> <T,U>(lhs: T, rhs: T -> U) -> U {
    return rhs(lhs)
}

This allows me to terminate a chain like so:

let result = array
  .filter { $0.isValid }
  .map(transform)
  .joined()
  |> someFunction

It would perhaps be better with

   // ...
   .joined()
   .apply(someFunction)

But at least you don't have to wrap the entire chain in a function call, and have your eyes alternate between parsing left-right and right-left when reading the code.

1 Like