c11ada c11ada - 1 year ago 102
Swift Question

Completion Handlers in Swift

I'm fairly new at swift development and trying to get a handle on closures and completion handlers. I have a function with the following declaration inside a struct called ObjectData

func getData(id1:Int, id2:Int, completion: (dataObject? -> Void))

I am trying to call this function like

ObjectData.getData(1, id2: 2){
(let myObject) in

but i get the following error

Cannot invoke 'getData' with an argument list of type '(NSNumber, id2:
NSNumber, (_) -> _)'

Please can someone help

Answer Source

For better readability, change the header to this. Remember that you have to declare types, not variable names:

func getData(id1:Int, id2:Int, completion: (ObjectData?) -> (Void))

Now I personally use this syntax to use closures:

self.getData(1, id2: 1) { (data) -> (Void) in

     // Some code executed in closure

If you want to study further, you can find full syntax of closures here (notice appropriate name of the website). Hope it helps!