Ios 强制转换到运行时确定的类
我想知道如何将对象强制转换为仅在运行时确定的类 让我们举一个例子:Ios 强制转换到运行时确定的类,ios,swift,casting,Ios,Swift,Casting,我想知道如何将对象强制转换为仅在运行时确定的类 让我们举一个例子: let xClasses = [ClassA.self, ClassB.self] let xClass = xClasses[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! xClass 因此,基本上,我有一个类数组,并希望在运行时从其中选择一个进行强制转换(在
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
}
很可能您还需要一个默认值:
在运行时确定的类型信息实际上称为
existentis
。你可以在这个博客中阅读更多信息。在swift2中,如果您不想使用开关盒,则必须使用协议。那么问题是什么?@ÖzgürErsil正如我所说的:如何强制转换到运行时确定的类。(类似于上述代码中的情况)您能告诉我在上述情况下如何使用协议进行强制转换吗?(我也使用开关作为解决方法;但我真的不喜欢它,因为有4-5个开关盒)