Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 在swift中使用协议和类名进行对象初始化_Objective C_Swift_Initialization_Protocols - Fatal编程技术网

Objective c 在swift中使用协议和类名进行对象初始化

Objective c 在swift中使用协议和类名进行对象初始化,objective-c,swift,initialization,protocols,Objective C,Swift,Initialization,Protocols,在Ojective-C中,我写道: id <MyProtocol> object = [[NSClassFromString(@"aClassName") alloc] initWithObject:obj]; id object=[[NSClassFromString(@“aClassName”)alloc]initWithObject:obj]; 我想用Swift写这封信 有没有同样的方法,还是我已经脱离了语言范式 编辑: 这是我的背景。 在我的某处: - (instance

在Ojective-C中,我写道:

id <MyProtocol> object = [[NSClassFromString(@"aClassName") alloc] initWithObject:obj];
id object=[[NSClassFromString(@“aClassName”)alloc]initWithObject:obj];
我想用Swift写这封信

有没有同样的方法,还是我已经脱离了语言范式

编辑:

这是我的背景。 在我的某处:

- (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;
}
-(instancetype)initWithObject:(NSArray*)数组和className:(NSString*)className{
self=[self initWithClassName:className];
如果(自我){
_members=[[NSMutableArray alloc]init];
for(数组中的id obj){
id object=[[NSClassFromString(className)alloc]initWithObject:obj];
[_membersaddobject:object];
};
}
回归自我;
}

在Swift中,您需要一个泛型类

类将有一个泛型类型
成员将是
[T]
类型,您可以使用
T
创建新实例


您不需要将
类名作为参数传递。

为了在类上调用该初始值设定项,您需要知道该类支持该初始值设定项。因此,让我们创建
MyProtocol
协议所需的初始值设定项:

protocol MyProtocol {
  init(object: AnyObject)
}
然后您只需执行
NSClassFromString
,然后将结果强制转换为
MyProtocol.Type
(以声明该类是
MyProtocol
的子类型),这允许您使用所需的初始值设定项:

let object = (NSClassFromString(className) as! MyProtocol.Type)(object: obj)

为什么要使用
NSClassFromString
?Swift是一种强类型语言。为什么要按名称使用类?请提供有关代码的更多信息。我使用的构造类不知道应用程序的其他类。我告诉这个类:“好的,现在你将用这个对象实例化,并且你将包含这种类型的对象。这类似于UITableView。你只能通过给类注册你的单元格。你为什么不给它类的名称,而不是给它类的名称(
class
)直接?可以很容易地转换成Swift。或者它是泛型的一个很好的用途?没有代码,很难判断。直接给类是指类对象还是直接给我的类?如果可以的话,我编辑了我的帖子。。。