Alan Alan - 22 days ago 4
Swift Question

get specific value from array to return in NSIndexpath.row

i want my collection view to return only specific array. i want it to return only from "AUDI" to "Chevrolet" or [2...9]. the car make and new car make array, both have value of 8. they both should be the same but it give me error

fatal error: Index out of bounds
. what did i do wrong??

var car make = ["Honda","Toyota","AUDI","Bentley","BMW","Mercedes","Buick","Cadillac","KIA","Chevrolet","Corvette","Dodge","FIAT","Ford","GMC","Hyundai","Infiniti","Jaguar","JEEP","LandRover","LEXUS","Mazda","Nissan","RAM","Porsche","Scion","Volkswagen"]

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return carmake[2...9].count

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = viewcontrol.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! jobtypeCollectionViewCell

let newcarmake = carmake[2...9]
cell.title.text = newcarmake[indexPath.row]
return cell


carmake[2...9] is not an array but an ArraySlice, and array slices use the same indices as the array that they are created from. So the valid indices for carmake[2...9] are 2...9, and not 0...7 as you probably expected.

One solution would be to create a real array instead:

let newcarmake = Array(carmake[2...9])
cell.title.text = newcarmake[indexPath.row]

Alternatively, reference the original array with a simple offset calculation, for example

cell.title.text = carmake[indexPath.row + 2]