Swift:是否可以将变量用于自定义类名?

时间:2015-08-08 16:03:03

标签: swift subclass

我正在尝试将CoreData变量用于我的大多数应用程序代码,但无法将它们用于自定义类的名称。以下是我的代码示例:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CREWWorkCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellName) as! CREWWorkCell

我想为CREWWorkCell使用一个字符串。这可能吗?

1 个答案:

答案 0 :(得分:1)

UITableViewController没有可以覆盖的CREWWorkCell函数。使用默认的UITableViewCell作为返回值,一切都可以正常使用自定义单元格。

在您的UITableViewController类中,使用以下函数:

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()
    }

使用Swift,您无法转换为动态类型(看看here)。因此,您无法使用例如:

转换为放入变量的类型
var myClassName = CREWWorkCell.self

var myClassName = CREWWorkCell().dynamicType

因为myClassName会在运行时进行评估,换句话说就是动态类型。但是,铸造操作员希望右侧有一个静态类型,这是一种已知的类型,并且不需要在运行时进行评估。此功能允许Swift强制实施类型安全。

我建议你以更简单的方式重新思考创建自定义单元格的方式。