Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to nest a function within another function in Objective-C

Tags:

c

objective-c

Objective-C is a superset of ANSI C. In GNU C, you can nest one function in another function... like this ...

float E(float x)
{
    float F(float y) //objective-C compiler says expected ; at end of declaration
    {
        return x + y;
    }
    return F(3) + F(4);
}

Is it possible to do this in Objective-C?

I know about blocks and NSInvocation objects, which could simulate the above C code. But can you define a function within the lexical scope of another function in Objective-C? Something like ...

-(int) outer:(int)x
{
    -(int) inner:(int)y //use of undeclared identifier inner
    {
        return x * 3;
    }
    return inner(x);
}
like image 720
bernie2436 Avatar asked Mar 07 '26 17:03

bernie2436


2 Answers

You can't, but you can easily get the same behavior with block

int outer(int i)
{
    int (^inner)(int) = ^(int x)
    {
        return x * 3;
    };

    return inner(i);
}
like image 144
Dmitry Shevchenko Avatar answered Mar 09 '26 07:03

Dmitry Shevchenko


You can't simply because in ObjectiveC methods are attached to classes like in C++, this means that there is always an implicit self inside a function.

How are you supposed to invoke a function that is nested inside another one? Making it a class method doesn't make much sense. Only way to invoke it would be by having it static (but it's seems really over complicating it)

You should use blocks, that are available to C, C++ and ObjectiveC on OS X or something similar like functors if you are going ObjectiveC++.

like image 33
Jack Avatar answered Mar 09 '26 07:03

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!