Map better in Swift

Map function is quite a convenience method that often used in functional(mainly) programming.

In Swift, all collection types(Array,Dictionary,Set…) support map. It take a closure that take element type from T and output type U then transform from [T] to [U].

In most case, you will see :

in short hand:

How convenience is that to old NSArray.

In real world case, things are more complicating.

Let’s say you have a type A, which can init from another type B. Now you have an array of [B], you would like to transform it to another array [A]. How would you do?

Typically, you may use the following code:

Easy.

Actually you make it better :

Sweet.

If you want to make it more functional, you can declare a operator for example <<< in this case.

Then you can:

Clean and clear.

There are still many other small but interesting skills in Swift that can help us code in a better way.

We will only observe them if we can free our mind from Objective-C age.

Like what you read? Give Matthew Lui a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.