How to pass data from child to parent view controller? in swift

I usually use closures for this purpose. Much simpler and less verbose than delegates:

class MainViewController: UIViewController {

    func showChildViewController() {
        guard let vc = storyboard?.instantiateViewControllerWithIdentifier("ChildViewController") as? ChildViewController else {
            return
        }
        vc.didSelectItem = { [weak self](item) in
            if let vc = self {
                // Do something with the item.
            }
        }
        presentViewController(vc, animated: true, completion: nil)
    }

}

class ChildViewController: UIViewController {

    var didSelectItem: ((item: Item) -> Void)?

    @IBAction func buttonPressed() {
        didSelectItem?(item: <#your item goes here#>)
    }

}

Leave a Comment