variable used before being initialized
You'll have the error because secondArrays
could be used without any initialization if your if let
fails.
Try the following logic:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destViewController = segue.destinationViewController as! SecondTableViewController
guard let indexPath = self.tableView.indexPathForSelectedRow else { return }
destViewController.secondArray = secondArrayData[indexPath.row].secondTitle
}
you can change the type of secondArrays
to an implicitly unwrapped optional (SecondTableData!
) and that should get rid of the build-time error. note if the the variable is not initialized and you try to access it, a runtime error will be thrown
also, if you change the variable to a let
this method won't work.
This is because of the way of initialising variables in Swift, In Swift Class each property need some default value before being used.
Class initialisation in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
Try changing your code as below:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destViewController = segue.destinationViewController as! SecondTableViewController
var secondArrays : SecondTableData?
if let indexPath = self.tableView.indexPathForSelectedRow {
secondArrays = secondArrayData[indexPath.row]
//Here you're making sure that the secondArrays would must have a value
destViewController.secondArray = secondArrays.secondTitle
}
}