john doe john doe - 3 months ago 14
Swift Question

Casting Issues in Swift

I have two UICollectionViewCells and I want to differentiate between the two. My RetroItemCollectionViewCell has a method called "configureFor". For some reason even if I cast it I am not able to call the "configureFor" function.

var cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

if cell is RetroItemCollectionViewCell {

cell = cell as! RetroItemCollectionViewCell
let retroItem = self.retroItems[indexPath.row]
cell.configureFor(retroItem: retroItem)

} else if cell is RetroItemAddCollectionViewCell {

}


What am I doing wrong?

UPDATE:

var cell :UICollectionViewCell!

// check if the cell is the add cell
if indexPath.row == 0 {

cell = collectionView.dequeueReusableCell(withReuseIdentifier: addRetroItemCollectionViewCellReuseIdentifier, for: indexPath) as! RetroItemAddCollectionViewCell


} else {

// HOW DO I CONVERT THE cell to RetroItemCollectionViewCell

let retroItem = self.retroItems[indexPath.row]

cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RetroItemCollectionViewCell

}

Answer

You're searching for the as? operator

The as? operator performs a conditional cast of the expression to the specified type. The as? operator returns an optional of the specified type. At runtime, if the cast succeeds, the value of expression is wrapped in an optional and returned; otherwise, the value returned is nil. - Swift Language Reference

var cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

if let cell as? RetroItemCollectionViewCell {
    let retroItem = self.retroItems[indexPath.row]
    cell.configureFor(retroItem: retroItem)
} else if let cell as? RetroItemAddCollectionViewCell {
    // ...
}
Comments