As I delve into learning JavaScript from Objective-C, I find myself pondering whether it is possible to have a method with parameter types in Objective-C. Let's take the example of the findIndex() JavaScript function that identifies and returns the index of the first array element passing a specified test function. How could this be implemented in Objective-C using blocks, if at all?
If I were to create a class category for NSArray, how would I go about passing a block to a method and applying that condition to the NSArray itself? If this is not feasible, I am eager to understand the reasons behind it.
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
I came across a valuable piece of information on StackOverflow regarding block syntax, which might aid in understanding the implementation of the findIndex() function.
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.