【问题标题】:Create class instances from an array of metatypes从元类型数组创建类实例
【发布时间】:2019-05-19 07:29:43
【问题描述】:

假设我确实有一个协议TestProtocol 和类TestClass1TestClass2 符合TestProtocol

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

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

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

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

p.s.:这应该在不创建检查 TestClass1.selfTestClass2.self 之类的开关结构的情况下完成

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

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

【问题讨论】:

    标签: swift polymorphism protocols metatype


    【解决方案1】:

    这行得通:

    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 约束)

    你能告诉我它是否适合你吗?如果没有,您需要更新您的工具链。

    【讨论】:

    • 为什么它们应该是结构体?
    • @Sander 我说“可能”是结构,不应该:)
    • 非常感谢。我认为在元类型上调用 init() 是不可能的。我可能不会很快看到那里。
    • 是的,它可以编译。刚刚意识到我没有在之前的评论中明确说明这一点。
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2021-06-30
    相关资源
    最近更新 更多