How is it possible to dynamically cast to a Type that is named in a string with Swift 2.0?

若如初见. 提交于 2020-01-03 17:03:37

问题


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)!

How is this possible in Swift 2.0? Thnx!


回答1:


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.

  • 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.




回答2:


You could use NSClassFromString to convert your string to the class you want, then you can use that to cast the tableviewCell



来源:https://stackoverflow.com/questions/34094293/how-is-it-possible-to-dynamically-cast-to-a-type-that-is-named-in-a-string-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!