创建具有从超类继承的值的字典

时间:2019-05-28 13:29:36

标签: swift

我有多个从单个类继承的类,是否可以为它们创建字典映射?因此,在给定字符串键的情况下,我可以引用正确的类。

let map = [String: EngineView] = [
  "google": GoogleView,
  "duckduckgo": DuckDuckGoView
]

GoogleViewDuckDuckGoView都是EngineView的子类,但是XCode抱怨:

“无法将类型“ GoogleView.Type”的值转换为预期的字典值类型“ EngineView””

1 个答案:

答案 0 :(得分:0)

假设GoogleViewDuckDuckGoView继承自EngineView,您可以执行以下操作:

let map = [String: EngineView.Type] = [
  "google": GoogleView.self,
  "duckduckgo": DuckDuckGoView.self
]

用法

if let aClass = map["google"] {
    let instance = aClass.init()
}