简体   繁体   中英

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

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!

Far away from my Mac now, so I can't test, but try this:

ObjectData.getData(1, id2: 2, (dataObject) -> { 
...code...
});

Also can't check now, but I think this also should work:

    ObjectData.getData(1, id2: 2)(dataObject){ 
...code...
}

尝试首先初始化您的类(例如var objectData = ObjectData()),然后使用objectData.getData调用函数......它应该以这种方式工作..

In SWIFT 3,It is known as completion closure.

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

    //Do the stuff before calling completion closure
    completion(value as? dataObject)   
}

ObjectData.getData(id1:1, id2: 2,completion:{(data) -> (Void) in
    //Do the completion stuff here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM