Functional Swift

Map
Map applies a function to every element in the array, and then returns a new array, such as:

Functionally, you can implement this with map as such:

Flatten
Flatten flattens out nested arrays, and unwraps optionals.

FlatMap
FlatMap does Map, then Flatten.

Reduce
Reduce takes an initial value, and a combine function, and combines all of the elements within an array.

Functionally, this could be done as follows:

Filter
Filter is exactly as it sounds, you pass in a function of type T -> Bool (where T is the type of the array), and it will remove any elements which return false.

Functionally:

Filter can be done to easily create quicksort:

It’s worth noting that this has to go through the array 3 times to filter, so you would be better off using pattern matching, however this is much simpler to read.

Putting it all together
You can combine all of these to do really complex actions in a single extremely readable command:

Pipe Operator

If you’re familiar with the pipe operator either in BASH or functional languages such as F# or Elixir, you’ll be happy to know it’s easy to implement in Swift:

This allows you to easily compose functions:

Tail Call Optimization

Swift supports tail call optimization, which means it doesn’t need to create a new stack frame if the last action the function takes before returning is calling itself.

Example:

Would roughly the same as (note, this doesn’t work as there is no goto in Swift):

Comments 1

  1. I had some suggestions about your 531 program app in iOS. I’d love to help you finish it out or release an alternative version. I know you’re busy but if you had some time, I’d love to chat.

    I hope everything is well, thanks your time 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *