Sobes.tech
Junior — Middle

Explain how function pointers work using an example of a function that contains another function inside it.

sobes.tech AI

Answer from AI

In iOS (Swift or Objective-C), the concept of function pointers is implemented through closures or blocks. In the C language, on which Objective-C is based, function pointers allow passing functions as parameters or storing them for later invocation.

Example in C with a function that contains another function inside it (via a nested function or a function returning a pointer):

#include <stdio.h>

// C does not have nested functions, but you can return a pointer to a function
int innerFunction(int x) {
    return x * x;
}

int (*outerFunction())(int) {
    // Return a pointer to innerFunction
    return &innerFunction;
}

int main() {
    int (*funcPtr)(int) = outerFunction();
    int result = funcPtr(5); // call innerFunction via pointer
    printf("Result: %d\n", result); // Output: Result: 25
    return 0;
}

In Swift, closures can be used:

func outerFunction() -> (Int) -> Int {
    func innerFunction(x: Int) -> Int {
        return x * x
    }
    return innerFunction
}

let funcPtr = outerFunction()
print(funcPtr(5)) // 25

Thus, function pointers allow dynamically selecting and calling functions, which is useful for callbacks and functional programming.