iOS Dev Nugget 300 Pipe Operator


Need to run a code review on your codebase? Hire me

I'm going to talk about something that Swift doesn't have.

I'm quite a fan of the pipe operator in Elixir where you can do:

"Elixir rocks"
    |> String.upcase()
    |> String.split()


Swift doesn't provide the pipe operator, but there are multiple implementations floating around that implements it using operator overloading. One of the libraries gives as an example:

let isEven: (Int) -> Bool = { x in x % 2 == 0 }
    .map({$0 * 3})
    .reduce(0, +)

which can be rewritten with the library's pipe operator as:

let isEven: (Int) -> Bool = { x in x % 2 == 0 }
    |> (filter, isEven)
    |> (map, {$0 * 3})
    |> (reduce, 0, +)

I just want to point out that. The pipe operator in Elixir (and F#) works in a different way. Let's look at an example. With the pipe operator in Elixir, you should be able to rewrite this code:

bar(foo([1, 2, 3, 4].map({ $0 == 2 })))


[1, 2, 3, 4].map({ $0 == 2 })
    |> foo
    |> bar

In other words, you kind of flip the code with nested function calls from right to left to left-to-right, so it's easier to understand without introducing local variables.

Just wanted to clear this up.

PS: Sorry, this issue is very late.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues