在Swift运行时创建一个已知类的实例 [英] Create instance of class known at runtime in Swift

查看:111
本文介绍了在Swift运行时创建一个已知类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一张图片值得一千字,如何将此代码从Objective-C重写为Swift?

A picture is worth a thousand words, how to rewrite this code from Objective-C to Swift?

- (id) instanceOfClass: (Class) class withInitializer: (SEL) initializerSelector withObject: (id) object {
    id obj = nil;
    if([class instancesRespondToSelector:initializerSelector]) {
        obj = [[class alloc] performSelector:initializerSelector
                                  withObject:object];
    }
    return obj;
}

id myViewController = [self instanceOfClass:[ViewController class]
                              withInitializer:@selector(initWithObject:)
                                   withObject:@"super-string!"];
NSLog(@"%@", myViewController);


推荐答案

这不能纯粹在Swift中完成。您只能在Objective C中创建类名称创建者的类实例,并从Swift中调用此代码。

This cannot be done purely in Swift. You can only do this by creating the "class instance by name creator" in Objective C and calling this code from Swift.

有关更多信息,请阅读本文。
http://ijoshsmith.com/ 2014/06/05 / instant -ating-classes-by-name-in-swift /

For more information you can read this article. http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/

查看这个github repo
https://github.com/ijoshsmith/swift-factory

And check out this github repo https://github.com/ijoshsmith/swift-factory

这篇关于在Swift运行时创建一个已知类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆