Search code examples
iosswiftsegue

How to properly use prepare for segue for Structs?


I cant access my Struct data given in VC1, in VC2, what am i missing here?

I have tried a bunch of stuff, and the only way im able to access the data is by declaring variable in VC2 like this: var contactsOfUser: ContactStruct?, however that gets me error in VC1 on Prepare for segue saying

Cannot assign value of type '[ContactStruct]' to type 'ContactStruct?'

Anyway here is my code, maybe i have messed up somewhere:

VC1:

//here i use performSegue:

DispatchQueue.main.async { [weak self] in
                        self?.performSegue(withIdentifier: "inviteFriends", sender: nil)


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


        if segue.identifier == "inviteFriends"{
            let dest = segue.destination as! LetsInviteFriendsViewController
            dest.contactsOfUser = self.contacts

        }


    }

VC 2:

    var contactsOfUser: ContactStruct?


        @IBOutlet weak var tableView: UITableView!

            override func viewDidLoad() {
            super.viewDidLoad()

            print(contactsOfUser?.givenName)

Solution

  • The error message is pretty clear. You are trying to pass an array of ContactStruct from VC1 and assign that array to the contactsOfUser property, which you declared as a single ContactStruct. Just change that to be an array.

    VC2: var contactsOfUser = [ContactStruct]()