从词典创建Swift对象 [英] Create a Swift Object from a Dictionary
本文介绍了从词典创建Swift对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据Swift中字典中的查找值动态实例化一个类型?
How do you instantiate a type dynamically based upon a lookup value in a dictionary in Swift?
推荐答案
希望这对他人有用。它需要一些研究来证明这一点。目标是避免巨型if或switch语句的反模式从一个值创建每个对象类型。
Hopefully this is useful to others. It took some research to figure this out. The goal is to avoid the anti-pattern of giant if or switch statements to create each object type from a value.
class NamedItem : CustomStringConvertible {
let name : String
required init() {
self.name = "Base"
}
init(name : String) {
self.name = name
}
var description : String { // implement Printable
return name
}
}
class File : NamedItem {
required init() {
super.init(name: "File")
}
}
class Folder : NamedItem {
required init() {
super.init(name: "Folder")
}
}
// using self to instantiate.
let y = Folder.self
"\(y.init())"
let z = File.self
"\(z.init())"
// now put it in a dictionary.
enum NamedItemType {
case Folder
case File
}
var typeMap : [NamedItemType : NamedItem.Type] = [.Folder : Folder.self,
.File : File.self]
let p = typeMap[.Folder]
"\(p!.init())"
let q = typeMap[.File]
"\(q!.init())"
有趣的方面:
Interesting aspects:
- 对初始化器使用必需
- 使用。键入以获取字典值的类型。
- 使用.self获取可以实例化的类
- 使用()来实例化动态对象。
- 使用可打印协议来获取隐式字符串值。
- 如何使用非参数化的初始化,并从子类初始化中获取值。
- use of "required" for initializers
- use of .Type to get the type for the dictionary value.
- use of .self to get the "class" that can be instantiated
- use of () to instantiate the dynamic object.
- use of Printable protocol to get implicit string values.
- how to init using a non parameterized init and get the values from subclass initialization.
更新为Swift 3.0语法
Updated to Swift 3.0 syntax
这篇关于从词典创建Swift对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文