0

I have a model that holds a bool value. I would like to return a UICollectionViewCell based on the value of the bool within the model using a switch statement. However, I am getting a casting error.

Could not cast value of type 'Project.FalseCell' (0x10077a9f0) to 'Project.TrueCell' (0x100777ef8).

I've checked the following;

  1. I have registered my cells in viewDidLoad
  2. I have unique identifiers for each cell type

What am I missing here?

// MODEL
struct Model {
    let bool: Bool
}

// CONTROLLER
let models = [Model]()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let model = models[indexPath.item]
    
    switch model.bool {
    case true:
        let trueCell: TrueCell = listView.collectionView.dequeueReusableCell(withReuseIdentifier: TrueCell.identifier, for: indexPath) as! TrueCell
        return trueCell
    case false:
        let falseCell: FalseCell = listView.collectionView.dequeueReusableCell(withReuseIdentifier: FalseCell.identifier, for: indexPath) as! FalseCell
        return falseCell
    }
}
David Henry
  • 1,972
  • 20
  • 43
  • 1
    as the error log, i think your TrueCell have problem: that it identifier when reuse will return a cell of type FalseCell – goat_herd May 04 '21 at 04:59
  • Yes you are right I had declared the identifier using String(describing: Self) however, I had renamed the custom cell class which had disturbed the identifier. – David Henry May 04 '21 at 05:02
  • so if you had your answer, you should update the question with the answer and close this question – goat_herd May 04 '21 at 08:47
  • Definitely casting to FalseCell is causing error. Check your FalseCell if its of FalseCell type. – Kudos May 04 '21 at 09:05

1 Answers1

0

As per @goat_herd 's comment, there was an issue with using cell identifiers as String(describing: Self) as I had renamed the Class at one point and this caused a disruption in the identifier.

I changed the identifier to a raw valued string and this solved the issue.

David Henry
  • 1,972
  • 20
  • 43