Cast object for the class stored in a variable

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() } } } 
+5
source share
1 answer

Perhaps this will help you:

Factory Method: The factory pattern is used to replace class constructors, to abstract the process of generating an object, so that the type of the object instance can be determined at runtime.

https://github.com/ochococo/Design-Patterns-In-Swift#-factory-method

-2
source

Source: https://habr.com/ru/post/1268777/


All Articles