Reputation: 4334
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
Upvotes: 3
Views: 1301
Reputation: 1712
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
}
Upvotes: 0
Reputation: 1600
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...
}
Upvotes: 1
Reputation: 5122
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!
Upvotes: 4
Reputation: 1252
try to initialize your class first (ex. var objectData = ObjectData()) , and then call function with objectData.getData... it should work that way ..
Upvotes: 0