加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在swift 3中从字符串创建类的实例

发布时间:2020-12-14 05:48:30 所属栏目:百科 来源:网络整理
导读:我尝试使用字符串以多种方式创建类的实例,但没有一个在Swift 3中工作. 以下是我尝试过的无法正常工作的Swift 3解决方案 – 使课程成为一个客观的课程 @objc(customClass)class customClass { ...}//Error here: cannot convert value of type 'AnyClass?' to
我尝试使用字符串以多种方式创建类的实例,但没有一个在Swift 3中工作.

以下是我尝试过的无法正常工作的Swift 3解决方案

– 使课程成为一个客观的课程

@objc(customClass)
class customClass {
    ...
}

//Error here: cannot convert value of type 'AnyClass?' to expected argument type 'customClass'
let c: customClass = NSClassFromString("customClass")

– 使用NSString值指定类(使用和不使用@objc属性)

@objc(customClass)
class customClass {
    ...
}

//Error here: cannot convert value of type 'String' to expected argument type 'AnyClass' (aka 'AnyObject.Type')
var className = NSStringFromClass("customClass")

let c: customClass = NSClassFromString(className)

我做的不对,但没有在网上找到任何解决方案.

如何在Swift 3中使用字符串创建类的实例?

你可以试试这个:
func stringClassFromString(_ className: String) -> AnyClass! {

    /// get namespace
    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;

    /// get 'anyClass' with classname and namespace 
    let cls: AnyClass = NSClassFromString("(namespace).(className)")!;

    // return AnyClass!
    return cls;
}

像这样使用func:

class customClass: UITableView {

    }   
let myclass = stringClassFromString("customClass") as! UITableView.Type
let instance = myclass.init()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读