gpt4 book ai didi

ios - 转换为在运行时确定的类

转载 作者:行者123 更新时间:2023-11-28 06:37:50 25 4
gpt4 key购买 nike

我想知道如何将对象转换为仅在运行时确定的类。

让我们举个例子:

let xClasses = [ClassA.self, ClassB.self]
let xClass = xClasses[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! xClass

所以基本上,我有一个类数组,并且想在运行时从其中一个类中选择一个进行转换(在这个例子中,是 UITableViewCell 的一个对象)。

(以上代码无效)我如何实现这一目标?

注意:我以这段代码为例,我的问题不仅仅是关于UITableViewCell。谢谢。

最佳答案

我的项目中有这样的东西。我使用开关盒来处理它。像这样:

switch xClass {
case is ClassA:
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ClassACell
case is ClassB:
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ClassBCell
}

您很可能还需要一个default:

在运行时确定的类型信息实际上称为Existentials。您可以在此博客中阅读更多信息 post .在 swift2 中,如果您不想要 switch case,则必须使用协议(protocol)。

关于ios - 转换为在运行时确定的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38697260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com