possen possen - 1 year ago 113
iOS Question

Create a Swift Object from a Dictionary

How do you instantiate a type dynamically based upon a lookup value in a dictionary in Swift?

Answer Source

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

let z = File.self

// 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]
let q = typeMap[.File]

Interesting aspects:

  • 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.

Updated to Swift 3.0 syntax

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download