How to create an instance of a type given its name?

I'd like to know if it's possible to instantiate a RawRepresentable type given its name.

For example:

enum Status: Int {
   case ready = 0
   case processing, error, done
}

I would like to get to the Status type and instantiate using a raw value:

let type = type(named: "Status")
let value = type.init(rawValue: 0)

Is this possible in Swift yet?

1 Like

The standard library has a _typeByName() function. However it's undocumented and unsupported. Evenutally, we will have an official mechanism for this purpose.

7 Likes

Thank you Slava. I'll give it a shot. I tried it quickly in a Playground but I may have the string for the type name wrong because it was returning nil.

I do have a workaround which may work for what I am doing. The intent is to create an enum value instance from its raw type given to me as an Any instance. The following seems to work.

enum Status: Int {
    case draft, ready, processing, done
}

enum MaritalStatus: String {
    case single, married, separated, divorced, widowed
}

func makeValueDecoder<A,B>(_ initializer: @escaping (A) -> B? ) -> (Any) -> Any? {
    return { value in
        guard let a = value as? A
            else {return nil}
        
        let b = initializer(a)
        return b as Any?
    }
}

let decoders: [String: (Any) -> Any? ] =
    [
               "Status": makeValueDecoder(Status.init(rawValue:))
        "MaritalStatus": makeValueDecoder(MaritalStatus.init(rawValue:)),
    ]


if let decoder = decoders["MaritalStatus"] {
    decoder("single")
}
if let decoder = decoders["Status"] {
    decoder(1)
}