In the code below, initialize the images in an array with a list of names. I want the order of the images to be aligned with the order of the array of names. This is what I tried and got an error saying:
Thread 1: EXC_BAD_INSTRUCTION ( code=EXC_I386_INVOP, subcode = 0x0)
The console says: fatal error: Array index out of range (lldb) Code
class NonameTableViewController: UITableViewController {
var Names = [" Ferro", "Korean", "HUH?","CatCafe", "UINITY", "FAKESTORE" ,"IRANOUTOFNAMES", "OKAY", "KEEP CODING"]
var Images = ["cafedeadend.jpg", "homei.jpg", "teakha.jpg", "cafelois1.jpg"," petiteoyster.jpg", "forkeerestaurant.jpg"]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIndentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIndentifier, forIndexPath: indexPath)
//configure cell
cell.textLabel?.text = Names[indexPath.row]
cell.imageView?.image = UIImage(named: Images[indexPath.row])
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Names.count
}
The problem is that the arrays do not have the same number of elements. The first one has 9 and the second one only 6. Therefore the line:
It will give you this error because you are trying to access an index of the array
Images
that does not exist, since the maximum you can access isImages.count - 1
. Try adding more names to the arrayImages
or removing names from the arrayNames
so that they both have the same number of elements.What I would do is check if there is information in those indexes before accessing it, for example:
By the way, by convention, variable names (Names, Images) should start with lowercase (names, images) ;)
I recommend that
Images.xcassets
you create a new group with the name of each image and add the images there. This would remove the array from the middlevar Images = ["cafedeadend.jpg" .....]
and you could use the name of the image as a name and to call the image.