Swift 2.0如何动态转换为在字符串中命名的Type? [英] How is it possible to dynamically cast to a Type that is named in a string with Swift 2.0?

查看:91
本文介绍了Swift 2.0如何动态转换为在字符串中命名的Type?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将返回值转换为需要保持动态的特定类型,例如

I need to cast a return value to a specific type that I need to keep dynamic, like

let cellType = "CellTypeToBeResolved"
cell = (tableView.dequeueReusableCellWithIdentifier("myID") as? CellTypeToBeResolved)!

在Swift 2.0中这怎么可能? 谢谢!

How is this possible in Swift 2.0? Thnx!

推荐答案

您无法做到,因为Swift故意(而不是)遗漏了两个难题:

You can't do it, because Swift is (deliberately) missing not one but two pieces of the puzzle:

  • 您不能将字符串转换为类.

  • You can't turn a string into a class.

更重要的是,您不能转换为表示为变量的类.强制转换为的类必须是文字类,即必须在编译时知道.编译器需要知道此强制转换是合法的,此外,它还需要在编译时知道如何处理此变量.如果希望能够将MyCoolTableCell实例消息发送到此单元格,则需要在代码中使用原义的MyCoolTableCell名称-不是字符串,不是包含类型的变量,而是类型为 itself 的变量.

More important, you can't cast down to a class expressed as a variable. The class to cast down to must be a literal class, i.e. it must be known at compile time. The compiler needs to know that this cast is legal, plus it needs to know at compile time how to treat this variable. If you want to be able to send MyCoolTableCell instance messages to this cell, you need to use the literal MyCoolTableCell name in your code — not a string, not a variable containg the type, but the type itself.

这篇关于Swift 2.0如何动态转换为在字符串中命名的Type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆