Access Array of Array Index in Collectionview swift

93 Views Asked by At

I have 4 different arrays:

var arrayFirst = ["1"]
var arraySecond = ["2"]
var arrayThird = ["3"]
var arrayFourth = ["4"]

Created a Single Array for collection view.

 var collectionArrayStr = [arrayFirst,arraySecond,arrayThird,arrayFourth]

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return collectionArrayStr.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ViewCell", for: indexPath) as! ViewCell

    print(collectionArrayStr[indexPath.row])
    //output:- (["1"])

    if let indexPathSlctedImage = collectionArrayStr[indexPath.row] as? [String] {
        cell.txtHeading.text = indexPathSlctedImage[indexPath.row] // No exact matches in call to subscript 
    }
    return cell
}

I followed the above approach to multiple arrays into a single array but I got the error when I access the index value I got the error given below:-

No exact matches in call to subscript

Question: How to get an index value in a single array?

Can someone please explain to me how to do this, I've tried with the above code but have no results yet. Please Correct me if I'm doing wrong.

Any help would be greatly appreciated

2

There are 2 best solutions below

0
Fahim Parkar On BEST ANSWER

You are creating array of array by using

var collectionArrayStr = [arrayFirst,arraySecond,arrayThird,arrayFourth]

What you should do is as below.

var collectionArrayStr : [String] = []
collectionArrayStr.append(contentsOf: arrayFirst)
collectionArrayStr.append(contentsOf: arraySecond)
collectionArrayStr.append(contentsOf: arrayThird)
collectionArrayStr.append(contentsOf: arrayFourth)

print("collectionArrayStr==\(collectionArrayStr)")

Output will be

collectionArrayStr==["1", "2", "3", "4"]

Now in cell use as below.

cell.txtHeading.text = collectionArrayStr[indexPath.row]
6
Vollan On

It looks like you are calling indexPath.row twice?

So you tell the collectionView the amount of sections and amount of rows in section. That means indexPath.section and indexPath.row.

    if let indexPathSlctedImage = collectionArrayStr[indexPath.section] as? [String] {
        cell.txtHeading.text = indexPathSlctedImage[indexPath.row] 
    }