How do you instantiate a type dynamically based upon a lookup value in a dictionary in Swift?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With