iOS Passing Data between View Controllers Passing data using closures (passing data back)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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



Got any iOS Question?