根据函数参数创建 class 的实例

Create instance of class based on function argument

假设我有三个 classes:

import Foundation

class A {

    init() {
      print("A")
    }

}

class B {

    init() {
        print("B")
    }

}

class C {

    init() {
       print("C")
    }
}

我想动态地传递一个字符串("A"、"B" 或 "C")作为函数参数,然后在函数体内创建一个实例class 我通过了。这可能吗?怎么样?

我尝试了这个(和其他变体)但没有成功:

func test(c:AnyObject){
    let _class = c()
    //...
}

test(c:A)

[更新]也许这个问题与@Code Different 提出的问题没有什么不同,但这个问题是老问题,而且语言发生了太多变化,人们应该尝试任何建议的解决方案,然后才能找到有效的解决方案今天

有一个基础 class 可行,我们称它为 BaseClass。需要使用的 类 会继承自 BaseClass.

然后,在您的函数中,您将传递所需的类型。

下面是演示此技术的代码片段:

class BaseClass { }

class A: BaseClass { ... }
class B: BaseClass { ... }
class C: BaseClass { ... }

func test(type: BaseClass.Type) {
    let someObject = type.init()
    // You can cast the object if required
}

test(type: A.self) // creates an object of class A
test(type: B.self) // creates an object of class B

编辑: 如果你真的需要一个字符串来转换你的类型,你可以考虑在调用 test 之前做一些工作。在 switch case 中获取类型,然后将其传递给 test 应该可以。

编辑:它也可以与协议一起使用,只要它定义了您需要的初始化程序,以及必须公开的每个函数:

protocol SomeProtocol: class {
    init()
    func someFunction()
}

class A {
    required init() {
        print("A")
    }
}

extension A: SomeProtocol {
    func someFunction() {
        print("Some function of A")
    }
}

class B {
    required init() {
        print("B")
    }
}

extension B: SomeProtocol {
    func someFunction() {
        print("Some function of B")
    }
}

class C {
    required init() {
        print("C")
    }
}

extension C: SomeProtocol {
    func someFunction() {
        print("Some function of C")
    }
}

func test(someType: SomeProtocol.Type) {
    let someObject: SomeProtocol = someType.init()
    someObject.someFunction()
}

test(someType: A.self) // creates an object of class A
test(someType: B.self) // creates an object of class B