Skip to content

Instantly share code, notes, and snippets.

@MarcoMig
Last active December 8, 2017 03:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarcoMig/393d14ceaed0312ee83a to your computer and use it in GitHub Desktop.
Save MarcoMig/393d14ceaed0312ee83a to your computer and use it in GitHub Desktop.
Swift: Async callback block pattern example
//ClassA it's the owner of the callback, he will trigger the callback when it's the time
class ClassA {
//The property of that will be associated to the ClassB callback
var callbackBlock : ((error : NSError?, message : String?, adress : String? ) -> Void)?
init() {
//Do Your staff
}
//Define your function with the clousure as a parameter
func yourFunctionWithCallback(#functionCallbackParameter : (error : NSError?,message : String?, adress : String?) -> ()) {
//Set the calback with the calback in the function parameter
self.callbackBlock = functionCallbackParameter
}
//Later On..
func callbackTrigger() {
self.callbackBlock?(error: nil,message: "Hello callback", adress: "I don't know")
}
}
/ClassB it's the callback reciver the callback
class ClassB {
@IBAction func testCallbackFunction(sender: UIButton) {
let classA = ClassA()
classA.yourFunctionWithCallback { (error, message, adress) -> () in
//Do your stuff
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment