Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the PrepareForSegue method to transfer an object which has an unknown type in the receiving controller?

I’m working on Xcode projects in Swift and I’m trying to transfer data from a "FirstViewController" to a "SecondViewController".

First of all, I receive some data by my user in the FirstViewController. I made a structure to put all these data in one single object that i try to transfer.

Here’s my code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecondViewController" {
            let sentData:typeOfMyStrcuture = myObject()
            let secondVC = segue.destination as! SecondViewController
            secondVC.sentData = sentData
        }
    } 

In my SecondViewController I have :

var sentData: typeOfMyStructure!

The problem is : since the type of the object i’m sending is unknown in my SecondViewController, i got the following error : "Cannot find type ‘typeOfMyStructure’ in scope".
I tried to write the same structure in my SecondViewController for it to recognize the type but I get this error : "Cannot assign value of type ‘FirstViewController.typeOfMyStructure’ to type ‘SecondViewController.typeOfMyStructure’

Thanks by advance for your precious help !

>Solution :

Two options:

  1. if typeOfMyStructure is created inside the first view controller declare in the second view controller

    var sentData: FirstViewController.typeOfMyStructure!
    
  2. Declare typeOfMyStructure outside of any view controller

Side note: Please name structs and classes with a starting capital letter

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading