What are all valid ways of writing closures that return nothing and accept no parameters in Objective-C and Swift?

前端 未结 2 360
执念已碎
执念已碎 2021-01-29 09:48

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 arg

2条回答
  •  醉话见心
    2021-01-29 10:17

    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.

提交回复
热议问题