Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable used before being initialized

Tags:

ios

swift

I m having a problem with this

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]
    }
    destViewController.secondArray = secondArrays.secondTitle    
}

I m having an error in the line

destViewController.secondArray = secondArrays.secondTitle

secondArrays used before being initialized

why am I getting that error? Please help, just a newbie with Swift. TIA

like image 372
Aoi Avatar asked Mar 07 '16 04:03

Aoi


3 Answers

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
  }

}
like image 68
Bharat Modi Avatar answered Nov 10 '22 23:11

Bharat Modi


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
}
like image 3
J.Wang Avatar answered Nov 10 '22 23:11

J.Wang


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.

like image 1
shoe Avatar answered Nov 10 '22 23:11

shoe