What is the property block declaration equivalent in swift of the following block property?

zumzum picture zumzum · Jun 30, 2014 · Viewed 12.2k times · Source

In Objective-C I do this:

@property (nonatomic, copy) void(^completion)(MyObject * obj);

What is the correct way to do this in swift?

Answer

Martin R picture Martin R · Jun 30, 2014

The corresponding closure property would be declared as

class MyClass {
     var completion : ((MyObject) -> Void)? // or ...! for an implicitly unwrapped optional
}

You can set the property like

completion = {
    (obj : MyObject) -> Void in
    // do something with obj ...
}

which can be shortened (due to the automatic type inference) to

completion = {
    obj in
    // do something with obj ...
}