Reputation: 11653
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;
}
Upvotes: 1
Views: 991
Reputation: 122489
In order for you to call that initializer on the class, you need to know that the class supports that initializer. So let's make the initializer required by the MyProtocol
protocol:
protocol MyProtocol {
init(object: AnyObject)
}
And then you can just do NSClassFromString
, then cast the result to MyProtocol.Type
(to assert that the class is a subtype of MyProtocol
), which allows you to use the initializer you want:
let object = (NSClassFromString(className) as! MyProtocol.Type)(object: obj)
Upvotes: 1
Reputation: 130132
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 use T
to create new instance.
You won't need to pass the className
as a parameter.
Upvotes: 1