ios - 实例化存储在元类型字典中的类

标签 ios swift dictionary reflection swift3

我遵循了 Make a Swift dictionary where the key is "Type"? 的解决方案创建可以使用类类型作为键的字典。 我想要做的是:我有一个字典应该存储类类型及其类类型(又名元类型)作为键:

class MyScenario {
    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()
    }
}

...问题在最后一行:

Constructing an object of class type 'MyScenario' with a metatype value must use a 'required' initializer.

看起来编译器在这一点上很困惑,因为我不能在那个赋值时使用“required”。有谁知道我将如何在 executeScenario() 中实例化 scenarioClass

最佳答案

这必须完成这项工作。

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"

关于ios - 实例化存储在元类型字典中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44453851/

相关文章:

ios - @"{\"详细信息\":\"好友请求已待处理。\"}"如何从此 json 字符串中检索值

ios - setNeedsDisplay 未调用drawRect

ios - 在 Xcode Workspace 中构建单个项目

ios - 更改现有 MKAnnotation 上的自定义图像

Swift 3 Oauth2 Imgur 刷新键 - 错误 400 "Invalid grant_type parameter or parameter missing"

ios - 无法跳转到关闭状态

python - 无法修复未对齐的结果

通过 testflight 与 COSMCtrl _foregroundAppActivity 共享时,iOSApp 崩溃传入包提供的 UUID 为零,在设备日志中发现现有错误

python - 快速字符串或 JSON 查找数据结构

vba - 在 Excel 中使用 VBA 通过索引 # 选择字典项