Reputation: 913
I am attempting to use CoreData variables for most of my app code but have not been able to use them for the names of custom classes. Here is an example of my code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CREWWorkCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellName) as! CREWWorkCell
I want to use a string for CREWWorkCell. Is this possible?
Upvotes: 0
Views: 305
Reputation: 18591
UITableViewController
doesn't have a function that returns CREWWorkCell
that you could override. Use the default UITableViewCell
as a return value and everything would work fine with custom cells.
In your UITableViewController class use the following function:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Note that the return value is UITableViewCell and not CREWWorkCell
//get the class name from the database and put it in a variable called myClassName. Then
if myClassName == "CREWWorkCell" {
let cell : CREWWorkCell = tableView.dequeueReusableCellWithIdentifier("cell identifier 1", forIndexPath: indexPath) as! CREWWorkCell //of course you should cast to your custom class to be able to use it
return cell
} else if myClassName == "AnotherCellClass" {
let cell : AnotherCellClass = tableView.dequeueReusableCellWithIdentifier("cell identifier 2", forIndexPath: indexPath) as! AnotherCellClass
return cell
}
//do the same if you have other custom classes etc...
return UITableViewCell()
}
With Swift you can't cast to a dynamic type (have a look here). Therefore, you can't cast to a Type that you put in a variable using for example :
var myClassName = CREWWorkCell.self
or
var myClassName = CREWWorkCell().dynamicType
because myClassName
would be evaluated at runtime, in other words it is a dynamic type. But the casting operator expects a its right hand side a static type, a type that is already known and doesn't need to be evaluated at runtime. This feature allows Swift to enforce type safety.
I would suggest you to rethink the way you create custom cells, in a much simpler way.
Upvotes: 1