Mike Mike - 7 months ago 8
Swift Question

Why indexPath.row doesn't work here?

I am adding values from the first TableView var savedUrls to the first section of var detailsInSection in second TableView. In prepareForSegue, Xcode shows " unresolved Identifier for 'indexPath'. How should I revise the codes?

In first View Controller:

var folderNames = [String]()

var savedUrls = [String]()

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let url = savedUrls[indexPath.row]

self.performSegueWithIdentifier(segueToDetailsTable, sender: url)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if segue.identifier == segueToDetailsTable {

let detailsVC = segue.destinationViewController as! DetailsViewController

detailsVC.detailsInSection[0].append(savedUrls[indexPath.row])

}
}


In Second View Controller:

var sectionTitles = ["WebSite", "Date Saved", "Document Used","Add Notes"]

var detailsInSection = [[String]() , [NSDate]() , [AnyObject]() , String]() ]

Answer

indexPath is not a variable defined or passed into prepareForSegue. You are on the right track though. Since you pass the url as the sender in performSegue..., you don't need an indexPath to reference the url. You can check that the sender was a String and use sender as the url that was selected.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let url = savedUrls[indexPath.row]

    self.performSegueWithIdentifier(segueToDetailsTable, sender: url)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if let url = sender as? String where segue.identifier == segueToDetailsTable {

        let detailsVC = segue.destinationViewController as! DetailsViewController

        detailsVC.detailsInSection[0].append(url)

    }   
}