Clarence Clarence - 3 months ago 8
Swift Question

Initial func in 1st view from 2nd view (swift)

I have a button on 2nd

, after pressing that button, I would like to dismiss the 2nd
and go back to the 1st view controller and immediately call a function that coded inside 1st
swift file.

May I know how can I do that? By segue?


There are many way to do this one of the best way is using protocol and delegate.

You can create one protocol and extend that protocol in your ViewController1. Now create the delegate of protocol in ViewController2 and pass reference of that delegate in the ViewController1's prepareForSegue method.

First create one protocol like this

protocol PassdataDelegate {

    func passData()

Now extend this protocol in ViewController1 like this and pass the reference of delegate in prepareForSegue method

class ViewController1 : UIViewController, PassdataDelegate {

    func passData() {
        //Here call your function 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "SegueIdentifier") {
             let destVC = segue.destinationViewController as! ViewController2
             destVC.delegate = self 

Now create the delegate object of protocolin ViewController2 like this

class ViewController2 : UIViewController {

    var delegate: PassdataDelegate?

    //Now call the method of this delegate in Button action
    @IBAction func buttonClick(sender: UIButton) {
         //Now dismiss the controller

Note: - Here i am passing stringbut you can pass any type of object that you have declare in your delegate method.