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

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

概述我尝试使用字符串以多种方式创建类的实例,但没有一个在Swift 3中工作. 以下是我尝试过的无法正常工作的Swift 3解决方案 – 使课程成为一个客观的课程 @objc(customClass)class customClass { ...}//Error here: cannot convert value of type 'AnyClass?' to expected arg 我尝试使用字符串以多种方式创建类的实例,但没有一个在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.Typelet instance = myclass.init()
总结

以上是内存溢出为你收集整理的如何在swift 3中从字符串创建类的实例全部内容,希望文章能够帮你解决如何在swift 3中从字符串创建类的实例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1051485.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存