我想将字符串转换为类类型。
func getViewController(sbName: String, vcName: String, vcType: String) -> UIViewController{
let classType = ????? //What to put here?
let sb = UIStoryboard(name: sbName, bundle: nil)
var vc = sb.instantiateViewControllerWithIdentifier(vcName) as classType
return vc
}
如果有人能引导我朝着正确的方向前进,我会非常感激!我觉得有办法做到这一点但却找不到办法。
答案 0 :(得分:2)
如果您只担心基于Objective-C的课程,可以使用NSClassFromString("ClassName")
但是,您的方法是显式返回UIViewController。将vc转换为类类型根本不会对你有所帮助。
也许通用方法对你更好:
func getViewController<T: UIViewController>(sbName: String, vcName: String) -> T {
let sb = UIStoryboard(name: sbName, bundle: nil)
var vc = sb.instantiateViewControllerWithIdentifier(vcName) as T
return vc
}
然后可以从您尝试将其分配给的变量推断出类型:
var viewController: MyViewController = getViewController("ASDF", "ASDF")