Home > OS >  How to use the PrepareForSegue method to transfer an object which has an unknown type in the receivi
How to use the PrepareForSegue method to transfer an object which has an unknown type in the receivi

Time:02-11

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 :

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 !

CodePudding user response:

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

  • Related