问题
I'm having trouble understanding closure syntax in Swift and Objective-C.
Can someone tell me all possible ways in both languages to write a closure which accepts no arguments and returns nothing?
回答1:
In Objective-C language
void (^closureA)(void) = ^{ };
In Swift language
let closureB: () -> ()
let closureC: () -> Void
回答2:
Since you ask for all and since C is within Objective-C's reach and since you specify no parameters, this also gets the job done.
void ( * f ) ( void ); // C function pointer
Above is purely academic and below for amusement, but with that you can do the following!
// Void block to void function pointer
void ( ^ block ) ( void ) = ^ {
NSLog ( @"You have been warned" );
};
void * p = & block;
long * q = ( long * )( * ( long * ) p );
long * r = q + 2; // Try 0, 1, 2 [crash crash voila!]
void ( * f ) ( void ) = ( void ( * )( void ) )( * r );
// You have been warned
f ();
This is extremely dangerous (and entertaining) but does illustrate the equivalence between the void block and function pointer.
来源:https://stackoverflow.com/questions/64614969/what-are-all-valid-ways-of-writing-closures-that-return-nothing-and-accept-no-pa