简体   繁体   中英

Cannot assign value of type 'UITableViewCell' to type '…Cell' error in swift

let cellIdentifier = "ChampionThumbnailCell"

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as? ChampionThumbnailTableViewCell

if cell == nil {
    cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
}

cell!.championNameLabel.text = championNames[indexPath.row]
cell!.championThumbnailImageView.image = UIImage(named: championThumbnail[indexPath.row])

return cell!
}

I want to use the above code to reuse UITableViewCell, but I got this error when build it.

It looks like thie: Cannot assign value of type 'UITableViewCell' to type 'ChampionThumbnailTableViewCell?'

Is there any solution could fix it?

(By the way, I'm not very good at English...)

Change your method to this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


let cellIdentifier = "ChampionThumbnailCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ChampionThumbnailTableViewCell


cell.championNameLabel.text = championNames[indexPath.row]
cell.championThumbnailImageView.image = UIImage(named: championThumbnail[indexPath.row])

return cell
}

Notice in third line I am using as! instead of as? showing compiler that you aren't confused about your cell being nil.

But if it turns out that your cell is nil, it should cause runtime error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM