Get NSClassFromString from Array of Strings - Swift

强颜欢笑 提交于 2019-12-25 01:43:11

问题


I am trying to write a function that loads a particular view controller from my array of string>. However I'm struggling with this concept in swift - I achieved this in 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];

How do I achieve this concept in Swift? As Class is not featured in Swift?


回答1:


For NSObject derived classes (e.g. for view controller classes), NSClassFromString() still works in Swift (see also the various answers to Swift language NSClassFromString).

I have added a conditional cast on the type to ensure that the created class is indeed a subclass of UIViewController. As a consequence, the compiler "knows" about the available init methods, and that the created instance is a 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)
    // ...
}

Update for Swift 3:

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



回答2:


Swift currently doesn't do much in the direction of reflection and metaprogramming. You'll have to resolve to using Objective-C to do this. You might want to have a look at Josh Smiths Swift Factory: http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/




回答3:


What you are trying to do is against type-safety. Swift is a type safe language and does not allow you to do that. It might be possible with using some ObjC runtime functions, but it is probably not the best way. If you really need this kind of stuff, use Swift and Objective-C together on the same project.



来源:https://stackoverflow.com/questions/26256125/get-nsclassfromstring-from-array-of-strings-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!