john doe
john doe

Reputation: 9660

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

}

Upvotes: 0

Views: 49

Answers (1)

Alexander
Alexander

Reputation: 63271

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 {
    // ...
}

Upvotes: 3

Related Questions