I have a class which hold the class types for other classes. And these classtypes are registered on runtime, so actually I will not know the Class type at compile time. But later I will be using these registered class types to create instance of them. Here is my class definition
class registeredClassTypes
{
var URLContext: AnyClass
var ParserContext: AnyClass
var ValidationContext: AnyClass
func setTypes(URLContext: AnyClass, ParserContext: AnyClass, ValidationContext: AnyClass ) {
self.URLContext=URLContext
self.ParserContext = ParserContext
self.ValidationContext = ValidationContext
}
}
Now, I mave have collection of such objects holding the types.
let classTypesObj = registeredClassTypes()
classTypesObj.setTypes(SomeClass.self, ParserContext: AnotherClass.self, ValidationContext: OneMoreClass.self)
And sometime I will need instance from these types. Although it is possible like below but using typecasting to class:
let requestType:SomeClass.Type = classTypesObj.URLContext as! SomeClass.Type
let obj = requestType.init() //successfully creates the object of 'SomeClass'
I have referred few blogs and came to know that object from meta type can not be created without typecasting.
But my problem is that I will not be knowing the class 'SomeClass' so I can not typecast it to 'SomeClass'. Is there any way to achieve this to resolve class type dynamically. I want something like this or any other way:
let requestType = classTypesObj.URLContext
let obj = requestType.init()
Referred this blog & this blog too but they are also typecasting it. Any other way to solve this problem is also acceptable