Last active
December 8, 2017 03:38
-
-
Save MarcoMig/393d14ceaed0312ee83a to your computer and use it in GitHub Desktop.
Swift: Async callback block pattern example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/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