QuickAccount123
QuickAccount123

Reputation: 189

Swift 3 - Get data back from segue

I have 4 views which contains a segue(it sends data from a json and store it in a variable called email) which i'm passing it like this:

A -> B(email) -> C(email)

... -> B(email) -> D(email)

So what i want to do is send back the information of the segue to:

C-> B

D-> B

Any idea how can i achieve this?

Upvotes: 0

Views: 784

Answers (2)

Dan Karbayev
Dan Karbayev

Reputation: 2920

The common way for passing data back is to use delegation. Delegation in Swift is done using protocols. So, for example, you declare the following protocol (please, use meaningful names for protocol and properties, the following is just an example):

protocol COrDDelegate {
  func willReturn(someString: String)
}

Then, you add corresponding delegate properties to C and D view controllers:

class C: UIViewController {
  weak var delegate: COrDDelegate?
  ...
}

(the same goes for D). You'll have to use weak modifier to avoid retain cycles. After that, call delegate's method right before dismissing the view controller:

func dismissMe() {
  self.delegate?.willReturn(someString: "Meaningful data")
  self.dismiss(animated: true, completion: nil)
}

In B, you implement the protocol:

extension B: COrDDelegate {
  func willReturn(someString: String) {
    print(someString)
  }
}

and assign the delegate property to C or D in prepare(for:sender:) segue preparation method (just like you are probably doing for email):

func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let c = segue.destination as? C {
    c.email = self.email
    c.delegate = self
  }
}

Hopefully, I was able to convey the general idea. Good luck!

Upvotes: 2

Joshua Kaden
Joshua Kaden

Reputation: 1230

I think you're after an unwind segue.

To quote the docs:

...use the segue object to fetch the view controller being dismissed so that you can retrieve data from it.

Please see Creating an Unwind Segue on the View Controller Programming Guide for iOS.

Upvotes: 2

Related Questions