Object initialization with protocol and class name in swift

1k views Asked by At

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;
}
2

There are 2 answers

0
Sulthan On BEST ANSWER

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.

0
newacct On

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)