Reputation: 53
I have data that I want to send to another view controller via a segue. I add some user selected data to an array in my first view controller inside of 'didselectrow' for a tableview, and in 'prepareforsegue' I attempt to set the first element of that array equal to a variable in my second view controller. However, I get an 'index out of range error' telling me that the array is empty, and I am not sure why.
Here is the first viewcontroller:
var selectedStores = [String]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedStores.append(stores[indexPath.row])
performSegue(withIdentifier: "showStoreDetailsSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("Prepare for segue called")
if segue.identifier == "showStoreDetailsSegue" {
let destinationVC = segue.destination as! StoreDetailsViewController
destinationVC.selectedStore = selectedStores[0]
}
}
Second viewcontroller (StoreDetailsViewController):
var selectedStore = String()
I have another viewcontroller doing the exact same thing, but the array is not empty inside the prepareforsegue function. I have the tableview cell connected to the secondviewcontroller through a segue called "showStoreDetailsSegue".
Upvotes: 1
Views: 94
Reputation: 536028
I have the tableview cell connected to the secondviewcontroller through a segue called "showStoreDetailsSegue".
That’s the problem. You are performing the segue twice, and the first time is before didSelect
is called.
One solution: Connect the segue from the view controller, not the cell.
Alternatively (and better), delete your didSelect
implementation itself. You don’t really need selectedStores
. Just use prepare
to find out what the selection is, and go from there.
Upvotes: 2