如何从 Swift 中的字符串创建类的实例 [英] How to create an instance of a class from a String in Swift

查看:59
本文介绍了如何从 Swift 中的字符串创建类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过以多种方式使用字符串创建类的实例,但没有一种方法可以在 Swift 3 中运行.

I have tried creating an instance of a class using a string in numerous ways with none of them working in Swift 3.

以下是我尝试过但不起作用的 Swift 3 之前的解决方案

- 使课程成为客观 C 课程

@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)

我没有做正确的事情,但没有在网上找到任何解决方案.

I'm not doing something right but have not found any solutions online.

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

推荐答案

你可以试试这个:

func classFromString(_ 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
}

像这样使用函数:

class customClass: UITableView {}   

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

这篇关于如何从 Swift 中的字符串创建类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆