mylogon mylogon - 1 year ago 69
Objective-C Question

Objective-C equivilent lambda expressions

I'm primarily an iOS dev, but have been doing some UI Unit Testing in Visual Studio in C#. I came across this in C#

var table = Driver.FindElements(By.TagName("table"));
return table.First(t => t.Displayed == true);

Now, in Objective-C I would probably get an array and then for loop over until I found an element that met my criteria and then return that, which is a bit messy.

Does anyone know of a nice neat equivilent of this lovely stuff from C#.

I've had experience with lambda expressions in Objective-C and used blocks, but the syntax for that is dreadful and worse than a little for loop.

If anyone can point me in the right direction, I would be most grateful.



Avi Avi
Answer Source

Objective-C is not known for it's pretty or terse syntax. The two options I've come up with are:

NSArray *a = @[ @1, @2, @3, @4 ];

NSLog(@">= 3: %@", [a filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF >= 3"]]);
NSLog(@">= 3: %@", [a filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id obj, id bindings) { return [obj integerValue] >= 3; }]]);

To take only the first object from either filtered array, just append .firstObject.

In Swift, it gets better, with nicer block syntax, better type inference and auto-closures.