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

。_饼干妹妹 提交于 2021-02-17 05:50:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!