ios - 将类型存储在变量中?

标签 ios swift types

所以我想知道是否可以将类型保存在变量中,以便稍后在同一函数中使用。

我的代码如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let object = array.item(at: indexPath.row) else {
        fatalError("Could not retrieve the table object")
    }

    if object.displayOnLeft {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: LeftSidedCell.className, for: indexPath) as? LeftSidedCell else {
            fatalError("Could not dequeue the left sided cell")
        }
        cell.object = object
        return cell
    } else {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: RightSidedCell.className, for: indexPath) as? RightSidedCell else {
             fatalError("Could not dequeue the right sided cell")
        }
        cell.object = object
        return cell
    }
}

但我认为这实际上很笨拙,因为 if 和 else 中的内容本质上是相同的,只是单元格的类型不同。

理想情况下,我想要的算法基本上是:

var type
if object.displayOnLeft {
   type = LeftSidedCell
} else {
   type = RightSidedCell
}

//Dequeue Cell with type

我知道这里有几个问题,首先,我不能声明一个没有类型的变量,而且我不确定一开始要给它分配什么类型。其次,检索类的类型也没有成果。

我已经尝试将它作为一个属性存储在对象中,并在我的自定义对象中的函数中返回它,以及以下的一些变体:

func getTypeOfCell<T:TranslationCellProtocol>() -> T.Type {
    if displayOnLeft {
        return LeftSidedCell.self
    } else {
        return RightSidedCell.self
    }
}

无论如何,我不确定这是否可行,或者我是否对概念有根本性的误解,但我们将不胜感激。

谢谢。

最佳答案

首先,编写一个实现className() 方法(或您将用于两个单元类的任何方法和属性)的协议(protocol),并让您的两个单元类都符合它

protocol YourCellProtocol {
    var object : YourObjectClass? { get set }
    static func className() -> String
}

class LeftSidedCell : YourCellProtocol {...)
class RightSidedCell : YourCellProtocol {...}

然后你就可以做类似的事情了

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let object = array.item(at: indexPath.row) else {
        fatalError("Could not retrieve the table object")
    }

    var type : YourCellProtocol.Type
    if object.displayOnLeft {
        type = LeftSidedCell.self
    } else {
        type = RightSidedCell.self
    }

    let cell = tableView.dequeueReusableCell(withIdentifier: type.className, for: indexPath)
    if let yourCell = cell as? YourCellProtocol
    {
        yourCell.object = object
    }

    return cell
}

关于ios - 将类型存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49818518/

相关文章:

ios - RestKit:如何处理空的 response.body?

ios - 如何使用 SWRevealViewController 禁用侧边栏菜单中的交互

php - Xcode 7 beta swift 使用未解析的标识符

ios - 下载外部网页,用js和css修改,然后加载到 View 中的最佳方法

java - 对应类型树

ios - 是否可以在滚动/缩放时连续跟踪 MKMapView 区域?

objective-c - 如何从popoverController访问navigationController?

ios - 刷新图像时显示带有 ActivityIndi​​cator 的图像

c# - 在 C# 中,如何在给定 List<Object> 时确定对象的类型?

c++ - 如何写一个无符号的短整型文字?