Is it possible to save the class type in a variable and later use this variable to cast the object to the type of this class?
It seems I can store the class type in a variable in an enumeration, but I was not able to pass this variable to create a new object for this type.
I have an enumeration of subclass types
enum FruitType: Int { case orange, apple, lemon, lime var className: Fruit.Type { switch self { case.orange: return Orange.self case.apple: return Apple.self case.lemon: return Lemon.self case.lime: return Lime.self } } }
I have subclasses for these game objects (Orange, Apple, Lemon and Lime), and they all inherit from "Fruit"
Later I try to use this variable to cast the object to this type, but it reports an error
error "Using the undeclared type 'fruitType'
func createFruit(fruitType: FruitType, name: String) { if let orange = self.childNode(withName: name) as? fruitType.className { self.orange = orange } etc... }
I also tried fruitType.className(self.childNode(withName: name)) with the same results
I looked through Generics, but could not find anything that would suit this situation.
EDIT to show an actual example
This question has been simplified to simplify the wording of the question. The true nature of how I handle this is that I load the SKS scene file as SKReferenceNode based on fruitType, and I need to use this SKReferenceNode accordingly
func loadFruit(fruitType: FruitType) { var fruit: Fruit! if let fruitFile = SKReferenceNode(filename: fruitType.fileName) { if let fruitNode = fruitFile.childNode(withName: fruitType.name) as? fruitType.className { fruitNode.setup() } } }