Search code examples
swiftruntimefoundation

Convert from Type to String and vice versa in swift


I have a generic response serializer:

class ResponseArraySerializer<Element: Ball> {

}

Is there any way to convert that to string, so I will store that string in Core Data database, and then to convert back? Typically I use it like this:

let redBallSerializer = ResponseArraySerializer<RedBall>()
requestInfo.responseSerializer = redBallSerializer

So I what to do the same after initialization from a string (so I can initialize the object when I have only string description of the class). Is it possible?


Solution

  • This SO answer describes how to use a dictionary to map a string to a class.

    You can do the same thing with the various strings you store. However, generics are a bit harder to manage.

    First, you need to make a Serializer protocol that ResponseArraySerializer conforms to. This protocol will have the required init:

    protocol Serializer {
        init()
    }
    

    You then have to add a required initializer to the serializer to satisfy the compiler:

    required init() {}
    

    Finally, create the mapping as a dictionary:

    let serializerMapping: [String: Serializer.Type] = [
        "redBallSerializer":ResponseArraySerializer<RedBall>.self
        "greenBallSerializer":ResponseArraySerializer<GreenBall>.self
    ]
    
    let serializerKey = "redBallSerializer"
    let redBallSerializer = serializerMapping[serializerKey]!.init()
    

    Creating a mapping for just the generic type itself does not seem to work, so you have to store the whole class.