I going over and trying to learn JavaScript from Objective-C, and I'm curious if having a method has a parameter type is possible in Objective-C. Below is an example of the findIndex() JavaStript function that takes a returns the index of the first element in an array that pass a test (provided as a function). What would an Objective-C implementation of this look like with blocks, if this is even possible?
If I am writing a class category on NSArray, how would I pass in a block to a method and execute that condition on itself (NSArray). If it's not possible, I'd love to know why.
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
Here is one helpful tidbit I found on another StackOverFlow question that might help with the block syntax. A the definition of the findIndex() function that I'm trying to implement.
Block Syntax
Block as a method parameter Template
- (void)aMethodWithBlock:(returnType (^)(parameters))blockName { // your code }Example
-(void) saveWithCompletionBlock: (void (^)(NSArray *elements, NSError *error))completionBlock{ // your code }Block as a method argument Template
[anObject aMethodWithBlock: ^returnType (parameters) { // your code }];Example
[self saveWithCompletionBlock:^(NSArray *array, NSError *error) { // your code }];Block as a local variable** Template
returnType (^blockName)(parameters) = ^returnType(parameters) { // your code };Example
void (^completionBlock) (NSArray *array, NSError *error) = ^void(NSArray *array, NSError *error){ // your code };Block as a typedef Template
typedef returnType (^typeName)(parameters); typeName blockName = ^(parameters) { // your code }
FindIndex() Definition
Array.prototype.findIndex ( predicate [ , thisArg ] )
NOTE predicate should be a function that accepts three arguments and returns a value that is coercible to the Boolean value true or false. findIndex calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns the index of that element value. Otherwise, findIndex returns -1.