Passing data using closures passing data back

suggest change

Instead of using the delegate pattern, that split the implementation in various part of the UIViewController class, you can even use closures to pass data back and forward. By assuming that you’re using the UIStoryboardSegue, in the prepareForSegue method you can easily setup the new controller in one step

final class DestinationViewController: UIViewController {
    var onCompletion: ((success: Bool) -> ())?

    @IBAction func someButtonTapped(sender: AnyObject?) {
        onCompletion?(success: true)
    }
}

final class MyViewController: UIViewController {
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
        guard let destinationController = segue.destinationViewController as? DestinationViewController else { return }
    
        destinationController.onCompletion = { success in
            // this will be executed when `someButtonTapped(_:)` will be called
            print(success)
        }
    }
}

This is an example of use and it’s better to use on Swift, Objective-C block’s syntax is not so easy to make the code more readable

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents