Passing data using closures passing data back

suggest change

Instead of using the delegate pattern, which splits the implementation across the UIViewController class, you can use closures to pass data back and forward. Assuming you’re using a UIStoryboardSegue, in prepareForSegue you can set up the new controller in one step. This sample is Swift 2.

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 is easier to read in Swift than the equivalent Objective-C block syntax.

Feedback about page:

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



Table Of Contents