我有多个从单个类继承的类,是否可以为它们创建字典映射?因此,在给定字符串键的情况下,我可以引用正确的类。
let map = [String: EngineView] = [
"google": GoogleView,
"duckduckgo": DuckDuckGoView
]
GoogleView
和DuckDuckGoView
都是EngineView
的子类,但是XCode抱怨:
“无法将类型“ GoogleView.Type”的值转换为预期的字典值类型“ EngineView””
答案 0 :(得分:0)
假设GoogleView
和DuckDuckGoView
继承自EngineView
,您可以执行以下操作:
let map = [String: EngineView.Type] = [
"google": GoogleView.self,
"duckduckgo": DuckDuckGoView.self
]
用法
if let aClass = map["google"] {
let instance = aClass.init()
}