实例化存储在元类型Dictionary中的类 [英] Instantiating classes stored in metatype Dictionary
问题描述
我已按照>制作Swift字典的解决方案其中键是类型"?,以创建可以使用类类型作为键的字典.我想做的是:我有一本字典,也应该存储具有其类类型(也称为元类型)作为键的类类型:
I've followed the solution at Make a Swift dictionary where the key is "Type"? to create dictionaries that can use a class type as keys. What I want to do is: I have one dictionary that should store class types with their class type (aka metatype) as keys, too:
class MyScenario {
static var metatype:Metatype<MyScenario> {
return Metatype(self)
}
}
var scenarioClasses:[Metatype<MyScenario>: MyScenario.Type] = [:]
然后我有方法来注册和执行方案:
Then I have methods to register and execute scenarios:
public func registerScenario(scenarioID:MyScenario.Type) {
if (scenarioClasses[scenarioID.metatype] == nil) {
scenarioClasses[scenarioID.metatype] = scenarioID
}
}
public func executeScenario(scenarioID:MyScenario.Type) {
if let scenarioClass = scenarioClasses[scenarioID.metatype] {
let scenario = scenarioClass()
}
}
...问题在最后一行:
... Problem is in the last line:
使用元类型构造类型为"MyScenario"的对象值必须使用必需"的初始化程序.
Constructing an object of class type 'MyScenario' with a metatype value must use a 'required' initializer.
由于我不能在该分配中使用必需",因此似乎编译器在这一点上感到困惑.有人知道我将如何在 executeScenario()
中实例化 scenarioClass
吗?
It looks like the compiler is confused at that point since I cannot use 'required' at that assignment. Does anyone have an idea how I would have to instantiate the scenarioClass
in executeScenario()
?
推荐答案
这必须完成.
import Foundation
struct Metatype<T> : Hashable
{
static func ==(lhs: Metatype, rhs: Metatype) -> Bool
{
return lhs.base == rhs.base
}
let base: T.Type
init(_ base: T.Type)
{
self.base = base
}
var hashValue: Int
{
return ObjectIdentifier(base).hashValue
}
}
public class MyScenario
{
var p: String
public required init()
{
self.p = "any"
}
static var metatype:Metatype<MyScenario>
{
return Metatype(self)
}
}
var scenarioClasses:[Metatype<MyScenario>: MyScenario.Type] = [:]
public func registerScenario(scenarioID:MyScenario.Type)
{
if (scenarioClasses[scenarioID.metatype] == nil)
{
scenarioClasses[scenarioID.metatype] = scenarioID
}
}
public func executeScenario(scenarioID:MyScenario.Type)
{
if let scenarioClass = scenarioClasses[scenarioID.metatype]
{
let scenario = scenarioClass.init()
print("\(scenario.p)")
}
}
// Register a new scenario
registerScenario(scenarioID: MyScenario.self)
// Execute
executeScenario(scenarioID: MyScenario.self)
// Should print "any"
这篇关于实例化存储在元类型Dictionary中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!