1

I have created a table view (Xcode 11, Swift 5) in which I have put a collection view and I have also created an array of images:

let badgesImages: [UIImage] = [

    UIImage(named: "Plastic Bottle Challenge bronze")!,
    UIImage(named: "Plastic Bottle Challenge silver")!,
    UIImage(named: "Plastic Bottle Challenge gold")!,
    UIImage(named: "Car Challenge bronze")!,
    UIImage(named: "Car Challenge silver")!,
    UIImage(named: "Car Challenge gold")!,

]

that is recalled here:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
        cell.badgesImageView.image = badgesImages[indexPath.item]


    return cell
}

I would need to have three images chosen by me from the array to fill one cell of the table view and I need to repeat the process for every cell. How can I do this? Thanks in advance!

1 Answers1

0
import Foundation

let badgesImages = [
    "Plastic Bottle Challenge bronze",
    "Plastic Bottle Challenge silver",
    "Plastic Bottle Challenge gold",
    "Car Challenge bronze",
    "Car Challenge silver",
    "Car Challenge gold"
]

extension Array {
       func pick(_ n: Int) -> [Element] {
         guard count >= n else {
             fatalError("The count has to be at least \(n)")
         }
         guard n >= 0 else {
             fatalError("The number of elements to be picked must be positive")
         }

         let shuffledIndices = indices.shuffled().prefix(upTo: n)
         return shuffledIndices.map {self[$0]}
     }
}

badgesImages.pick(3) 

Example Referance

eildiz
  • 487
  • 1
  • 7
  • 14