swift - 从元类型数组创建类实例

标签 swift polymorphism protocols metatype

假设我确实有一个协议(protocol) TestProtocol 和符合 TestProtocol 的类 TestClass1TestClass2:

protocol TestProtocol: AnyObject { }
class TestClass1: TestProtocol { }
class TestClass2: TestProtocol { }

进一步假设我确实定义了一个元类型数组

var testArray: [TestProtocol.Type] = [TestClass1.self, TestClass2.self]

如何根据 testArray 的条目创建 TestClass1TestClass2 的实例对象?

p.s.: 这应该在不创建再次检查 TestClass1.selfTestClass2.self 的 switch 结构的情况下完成

var instanceArray: [TestProtocol] = []
for element in testArray {
    if element == TestClass1.self {
        instanceArray.append(TestClass1())
    } else if element == TestClass2.self {
        instanceArray.append(TestClass2())
    }
}

我研究了泛型,但没有找到合适的解决方案,因为元类型存储在 [TestProtocol.Type] 类型的数组中。

最佳答案

这个有效:

protocol TestProtocol: AnyObject {
    init()
}

final class TestClass1: TestProtocol { }
final class TestClass2: TestProtocol { }

var testArray: [TestProtocol.Type] = [TestClass1.self, TestClass2.self]

for testType in testArray {
    let testInstance = testType.init()
}

final classes 也可以是 structs(但您需要删除 AnyObject 约束)

如果它为你编译,你能告诉我吗?如果没有,您需要更新您的工具链。

关于swift - 从元类型数组创建类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840505/

相关文章:

ios - 隐藏 iOS 自定义键盘上的键盘快捷键栏

matlab - 如何在 MATLAB 中创建抽象类对象数组?

swift - 在仅了解协议(protocol)的情况下在泛型中调用泛型

ios - 联系人选择器的委派设置不正确

ios - JSQMessage传出气泡对齐问题

Swift:为什么 CGImageCreateWithImageInRect() 会创建一个大 1 像素的矩形?

java - Hibernate 多态查询

c# - 根据子类指定基类抽象方法的返回类型

ios - 使 swift 协议(protocol)符合 Hashable

embedded - 简单的串行点对点通信协议(protocol)