Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 723
headkit Avatar asked Jan 07 '23 01:01

headkit


1 Answers

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.

like image 89
matt Avatar answered Jan 09 '23 15:01

matt