如何创建一个包含类型的数组?

我正在尝试创建一个数组,其中包含我想要deque的自定义collectionView单元格的类。 下面我提供了一个如何使用这个数组的例子。 cellType是一个包含我想要deque的类的变量,而cellClass是一个包含不同类的数组。 我已经看到了类似的问题,但所有的答案似乎建议使用类的实例,如className.self。 是否可以创建这样的数组。 谢谢。

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cellType = cellClass[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! cellType cell.addRemoveCellDelegate = self cell.label.text = "\(indexPath)" switch indexPath.item { case 0: cell.backgroundColor = .magenta cell.screenLabel.text = screens[0] case 1: cell.backgroundColor = .purple cell.screenLabel.text = screens[1] case 2: cell.backgroundColor = .yellow cell.screenLabel.text = screens[2] case 3: cell.backgroundColor = .green cell.screenLabel.text = screens[3] default: cell.backgroundColor = .blue } return cell } 

首先,我建议您创建一个管理器文件。

 import Foundation class CollectionViewManager: NSObject { public var cells: [CellModel] = [] override init() { super.init() fillCells() } fileprivate func fillCells() { let arrayCellModels: [CellModel] = [ RowModel(type: .cellOne, title: "My First Cell"), RowModel(type: .cellTwo, title: "My Second Cell"), RowModel(type: .cellThree, title: "My Third Cell") ] arrayCellModels.forEach { (cell) in cells.append(cell) } } } protocol CellModel { var type: CellTypes { get } var title: String { get } } enum CellTypes { case cellOne case cellTwo case cellThree } struct RowModel: CellModel { var type: OptionsCellTypes var title: String init(type: CellTypes, title: String) { self.type = type self.title = title } } 

在ViewController中,您应该初始化您的经理。 这样的事情。

 class ViewController: UICollectionViewController { let collectionViewManager = CollectionViewManager() // your code here } 

接下来,您将创建一个ViewController扩展。

 extension ViewController: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // number of items from your array of models return collectionViewManager.cells.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // init item let item = collectionViewManager.cells[indexPath.item] // than just switch your cells by type switch item.type { case .cellOne: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellOne.self), for: indexPath) as! CellOne { cell.backgroundColor = .red return cell case .cellTwo: let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellTwo.self), for: indexPath) as! CellTwo { cell.backgroundColor = .blue return cell case .cellThree let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CellThree.self), for: indexPath) as! CellThree { cell.backgroundColor = .yellow return cell } } }