Completion Handlers in Swift
I'm new to rapid development and am trying to get information about closures and completion handlers. I have a function with the following declaration inside a structure called ObjectData p>
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 am getting the following error:
Cannot call 'getData' with argument list like '(NSNumber, id2: NSNumber, (_) -> _)'
Please help someone help
+3
source to share
4 answers
For better readability, change the title to this. Remember, you need to declare types, not variable names:
func getData(id1:Int, id2:Int, completion: (ObjectData?) -> (Void))
I now use this syntax to use closures:
self.getData(1, id2: 1) { (data) -> (Void) in
// Some code executed in closure
}
If you'd like to explore further, you can find the complete syntax for closures here (note the corresponding website name). Hope this helps!
+4
source to share
In SWIFT 3, it is known as the completion of the close.
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
}
0
source to share