Search code examples
arraysswiftuitableviewsegue

How to pass value from 2d array with prepareForSegue


I have a array like this in a tableView:

var array: [[String]] = [["Apples", "Bananas", "Oranges"], ["Round", "Curved", "Round"]]

I would like to pass on the name of the cell when the cell is pressed. With a standard array I would do this:

 let InfoSegueIdentifier = "ToInfoSegue"

    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.identifier == InfoSegueIdentifier
        {
            let destination = segue.destination as! InfoViewController
            let arrayIndex = tableView.indexPathForSelectedRow?.row
            destination.name = nameArray[arrayIndex!]
          }
    }    

And in the next ViewController (InfoViewController)

var name = String()


    override func viewDidLoad() {
        super.viewDidLoad()
nameLabel.text = name
    }    

Error: "Cannot assign value of type '[String]' to type 'String'"


Solution

  • Change this part of code

    if segue.identifier == InfoSegueIdentifier
    {
         let destination = segue.destination as! InfoViewController
         let arrayIndex = tableView.indexPathForSelectedRow?.row
         destination.name = nameArray[arrayIndex!]
    }
    

    To

    if segue.identifier == InfoSegueIdentifier
    {
       let destination = segue.destination as! InfoViewController
       let arrayIndexRow = tableView.indexPathForSelectedRow?.row
       let arrayIndexSection = tableView.indexPathForSelectedRow?.section
       destination.name = nameArray[arrayIndexSection!][arrayIndexRow!]
     }
    

    Try and share the results.

    Reason For crash: In your first viewController you have [[String]] which is the datasource for your section. Now, when you try to get the object from this array it will returns you [String] and in your destination viewController you have the object of type String. and while assigning [String] to String it cause the crash with type mismatch. So, what above code does is, it will take first [String] from the arrayIndexSection and then the String from arrayIndexRow and thus pass a String object to destination.

    Hope it clears.