20

In Objective-C I do this:

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

What is the correct way to do this in swift?

zumzum
  • 17,984
  • 26
  • 111
  • 172
  • 1
    possible duplicate of [swift : Closure declaration as like block declaration](http://stackoverflow.com/questions/24133797/swift-closure-declaration-as-like-block-declaration) – Martin R Jun 30 '14 at 17:03
  • I've looked at that answer, I wasn't able to understand how to apply the solution given to this specific case – zumzum Jun 30 '14 at 17:21
  • Is this how I could do it in Swift? var completion = { (obj: MyObject) -> Void in } – zumzum Jun 30 '14 at 17:39
  • The other question is slightly different (not about properties), therefore I have removed my closing vote. – Martin R Jun 30 '14 at 18:09

1 Answers1

45

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 ...
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382