问题
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