back home

Why you don't need functional programming in Objective-C

I love Objective-C ;-) Coming from a Java world one of the first questions that popped into my mind - is there any functional programming available - you know the usual stuff - filter, find, transform. The things you can’t live when programming in Java after you learn how cool they are (especially Guava).

Seems Objective-C has some nice features too in this area, maybe they don’t exactly match 1:1 to Java approach.

Like for example consider creating a cache for objects, like you want to speed up lookups for profiles by name, here’s what you can do:

NSDictionary *profilesByName = [NSDictionary dictionaryWithObjects:profiles forKeys:[profiles valueForKey:@”name”]];

Profiles is a NSArray when you call valueForKey on it it will iterate over all elements and using key value coding (KVC) ask nicely about property name. It can talk to any object implementing KVC which is awesome!

There’s a great way to filter stuff like:

NSArray *array = @[ @{ @”email” : @”filter string”} ];

NSArray *filteredarray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@”(email == %@)”, @”filter string”]]; 

Here’s the code will match any entries in the array that have a matching e-mail, and once again you can do this for any object implementing KVC.

How awesome is that?

It’s not all there’s more because NSPredicate is a really powerful mechanism. Check out NSPredicate post on NSHipster.

That’s not all there are also KVC operators that allow you to create one-liners for stuff like counting the average, finding max or min values. There’s a great NSHipster post about it.

And if that’s not enough for your there are libraries like FunctionalKit that bring in advanced stuff like Eithers, Options, anonymous functions, mappers, etc.