I have a rather strange case of downcasting failure that I cannot understand.
I have almost identical code in two UITableViewController
s. ProjectTableViewController
displays list of Project
, and its datasource is [Project]
. NewsfeedsTableViewController
displays list of Newsfeed
, but Newsfeed
can contain different types of source data, including Project
.
Depending on the type of the source data, each cell of NewsfeedsTableViewController
is downcasted to appropriate subclass of UITableViewCell
.
ProjectTableViewCell
a subclass of UITableViewCell
, and is used in both ProjectTableViewController
and NewsfeedsTableViewController
.
Now the interesting thing is, the code works without issue in ProjectTableViewController
but crashes in NewsfeedsTableViewController
, giving following error message:
Could not cast value of type 'UITableViewCell' (0x102e68128) to 'sample_app.ProjectTableViewCell' (0x1010ce6d0).
I have following codes in each class:
ProjectTableViewController.swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let project = projects[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("ProjectTableViewCell") as! ProjectTableViewCell
cell.projectTitle.text = project.title
cell.projectKeywords.text = project.keywords
return cell
}
NewsfeedsTableViewController.swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let newsfeed = self.newsfeeds[indexPath.row]
switch newsfeed.newsfeedableType {
case "Project":
let cell = tableView.dequeueReusableCellWithIdentifier("NewsfeedTableViewCell") as! ProjectTableViewCell
let source = newsfeed.newsfeedable as! Project
cell.projectTitle.text = source.title
cell.projectKeywords.text = source.keywords
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("NewsfeedTableViewCell")!
cell.textLabel!.text = newsfeed.newsfeedableType + String(newsfeed.id)
return cell
}
}
I would love to understand what's causing this issue.