swift类名和字符串互转

一、类名转字符串

class func swiftStringFromClass(cls : AnyClass) -> String{

       let str : String = NSStringFromClass(cls)

       return str

二、字符串转类名

1.转类名

class func swiftClassFromString(className: String) -> AnyClass! {

         let cls : AnyClass? = NSClassFromString(className)

        assert(cls != nil, "class not found,please check classname")

        return cls

2.实例化,以实例化UIViewController为例

let vcClass : AnyClass? = NSClassFromString(appName.ClassName)

guard let VC = vcClass as? UIViewController.Type   else {

return

}

let vc = VC.init()

你可能感兴趣的:(swift类名和字符串互转)