我try 过用多种方法创建一个类的实例,使用字符串,但没有一种方法有效.

Below are pre-Swift 3 solutions I have tried that are not working

- Making class an objective-c class

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

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

- Specifying class using NSString value (both with and without using @objc attribute)

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

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

How do I create an instance of a class using a string in 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
}

像这样使用func:

class customClass: UITableView {}   

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

Swift相关问答推荐

我应该在自定义存储队列上使用弱self 吗?

如何在HStack中均匀分布视图?

按变换zoom 在UIView中不起作用

SwiftUI - NavigationLink(value:)和navigationDestination不工作

在visionOS 1.0中已弃用';base Color';:请改用`Color`属性

是否在字符串属性上搜索数组和子数组?

expose 不透明的底层类型

如何隐藏集合视图中特定的单元格,以避免出现空白空间?

如何使用 Swift 在非本地函数中切换()一个 Bool?

NavigationStack 和 TabView - 工具栏和标题不显示

Swift // Sprite Kit:类别位掩码限制

如何在 Combine 合并运算符的输出上使用 eraseToAnyPublisher

如果 Swift 无法分配内存会怎样?

将内容与工作表顶部而不是中间对齐

iOS SwiftUI - 无法转换 ObservedObject 类型的值

Swift中的分段错误

无法从自定义动态框架(Swift)访问类

在 SwiftUI 中,如何在 UIView 内或作为 UIView 使用 UIHostingController?

在 Swift 中返回实例类型

UICollectionView 自定义单元格在 Swift 中填充宽度