Get class by name

99封情书 提交于 2021-01-27 21:11:24

问题


Can I get a class by its name? For example:

class Foo {

}

class Bar {

}

let x = "Foo"
classByString(x) // need to return Foo

I want to use metaprogramming to reduce code maintenance.


回答1:


You can use a NSClassFromString:

if let anyObj : AnyObject.Type = NSClassFromString("MyAppName.MySwiftClassFoo") {
   //call Foo
} else {
   //call Bar
}


来源:https://stackoverflow.com/questions/42081970/get-class-by-name

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