In Ojective-C I wrote:
id <MyProtocol> object = [[NSClassFromString(@"aClassName") alloc] initWithObject:obj];
I would like to write this in Swift.
Is there to do the same or am I out of the language paradigm ?
edit :
Here's my context. Somewhere I have :
- (instancetype)initWithObject:(NSArray *)array andClassName:(NSString *)className {
self = [self initWithClassName:className];
if(self) {
_members = [[NSMutableArray alloc] init];
for(id obj in array) {
id <MyProtocol> object = [[NSClassFromString(className) alloc] initWithObject:obj];
[_members addObject:object];
};
}
return self;
}
In Swift, you will need a generic class.
You class will have a generic type
<T : MyProtocol>
,members
will be of type[T]
and you can useT
to create new instance.You won't need to pass the
className
as a parameter.