Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Swift Object from a Dictionary

Tags:

dynamic

ios

swift

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

like image 747
possen Avatar asked Sep 30 '22 16:09

possen


1 Answers

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:

  • 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

like image 65
possen Avatar answered Oct 03 '22 02:10

possen