从字典创build一个Swift对象

如何基于Swift中的字典中的查找值dynamic地实例化types?

希望这对其他人有用。 花了一些研究来解决这个问题。 目标是避免巨大if或switch语句的反模式从一个值创build每个对象types。

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())" 

有趣的方面:

  • 初始化程序使用“必需”
  • 使用.Type来获取字典值的types。
  • 使用.self来获得可以实例化的“类”
  • 使用()来实例化dynamic对象。
  • 使用Printable协议来获取隐式string值。
  • 如何初始化使用非参数化的init并从子类初始化中获取值。

更新为Swift 3.0语法