从字符串数组中获取NSClassFromString - Swift

时间:2014-10-08 11:44:31

标签: ios class uiviewcontroller swift

我正在尝试编写一个从我的字符串>数组中加载特定视图控制器的函数。然而我在swift中正在努力解决这个问题 - 我在Objective-C中实现了这个目标。

static NSString const *const viewControllerClassName[3] = {@"one", @"two", @"three"};

// get the name of the class of the viewcontroller that will be shown on this page
const NSString *className = viewControllerClassName[1];
Class class = NSClassFromString((NSString *)className);

UIViewController *controller = [[class alloc] initWithContainer:self];

如何在Swift中实现这个概念?因为Swift中没有Class?

3 个答案:

答案 0 :(得分:2)

对于NSObject派生类(例如,对于视图控制器类),NSClassFromString()仍可在Swift中使用 (另见Swift language NSClassFromString的各种答案。)

我在类型上添加了条件转换 确保创建的类确实是UIViewController的子类。 因此,编译器“知道”可用的init方法,以及 创建的实例是UIViewController

let viewControllerClassName = [ "one", "two", "three"]

let className = viewControllerClassName[1]
if let theClass = NSClassFromString(className) as? UIViewController.Type {
    let controller = theClass(nibName: nil, bundle: nil)
    // ...
}

更新 Swift 3:

if let theClass = NSClassFromString(className) as? UIViewController.Type {
    let controller = theClass.init(nibName: nil, bundle: nil)
    // ...
}

答案 1 :(得分:0)

斯威夫特目前在反思和元编程方面做得不多。您必须决定使用Objective-C来执行此操作。你可能想看看Josh Smiths Swift Factory:http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/

答案 2 :(得分:-1)

您要做的是反对类型安全。 Swift是一种类型安全的语言,不允许你这样做。使用一些ObjC运行时函数可能是可能的,但它可能不是最好的方法。如果你真的需要这种东西,可以在同一个项目中同时使用Swift和Objective-C。

相关问题