I am faced with an issue regarding porting objC code to Swift.
What I'm trying to do is to allocate and init an object from a class type.
This is how i do in ObjC
-(id)getExistingVCFromClass:(Class)classVC
{
return ([dict objectForKey: NSStringFromClass([classVC class])]);
}
-(void)storeExistingVCForClass:(id)referenceToVC ForClass:(Class)classVC
{
[dict setObject:referenceToVC forKey:NSStringFromClass([classVC class])];
}
-(void)retrieveObject:(Class)classVC
{
//check if we have a previous one
id existingVC;
if ((existingVC = [self getExistingVCFromClass:classVC]))
{
//i retrieved some object matching the class
}
else
{
// found nothing -> init a new instance
id newVC= [[classVC alloc] init];
[storeExistingVCForClass: newVC ForClass:classVC];
}
}
This is working perfectly.in ObjC.
Now in Swift I have this :
func getExistingVCFromClass(type:AnyClass) -> AnyObject?
{
return (dict?.objectForKey(NSStringFromClass(type)));
}
func storeExistingVCForClass(object:AnyObject, type:AnyClass)
{
dict?.setObject(object, forKey: NSStringFromClass(type));
}
func retrieveObject(type:AnyClass)
{
var myObj:AnyObject?;
myObj = self.getExistingVCFromClass(type);
if (myObj == nil)
{
// not found -> init , but i dont know how!!
let newObject:AnyObject = type(); -> not compiling
let newObject:AnyObject = type.new(); -> not compiling
}
}
I can't find how to init my new instance if I provide the class. How can I solve this in Swift ?
Also, in objC i didn't have to send any parameter to the init, because the .xib file was loaded automatically with the viewcontroller.
In Swift, it seems it doesn't load automatically the .xib file, so I add those inits to all my viewcontrollers
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
{
super.init(nibName: nibNameOrNil, bundle: nil)
}
and I have to instantiate my viewcontroller like this (giving in parameter the nib filename):
let myVC = MyViewController(nibName: "MyViewController", bundle: nil);
So I would need to
- 1) Instantiate from an anonymous class
- 2) Give it some parameter
Any hint on how to achieve this would be greatly appreciated.
Thx.