0

Is there a way in Swift to take an instance of AnyClass and use that to declare an array of that type?

For example, I'm using Overcoat and Mantle to map JSON responses into models that are persisted in CoreData by the frameworks. Before I do a get request, I manually perform a fetch request on the Core Data context and receive back all the persisted models. I then have to use MTLManagedObjectAdapter which turns NSManagedObjects into plain models and back, to map the results from the fetch request into my model objects.

To that end, I made a function that I defined on the base model class:

class func mapResults(results: [NSManagedObject], toModelClass modelClass: AnyClass) -> ([AnyObject], [NSError?]) {
    var transformed: [AnyObject] = []
    var errors: [NSError?] = []
    for result in results {
        var error: NSError? = nil
        var model: AnyObject! = MTLManagedObjectAdapter.modelOfClass(modelClass, fromManagedObject: result, error: &error)
        transformed.append(model)
        errors.append(error)
    }
    return (transformed, errors)
}

I would love to be able to declared transformed as var transformed: [modelClass] = [] but for obvious reasons that doesn't work. Is there any way to convert that AnyClass object into a type or is it just not possible right now in Swift?

1 Answer 1

2

In this case, you can use Generics:

class Mapper {
    class func mapResults<T: AnyObject>(results: [NSManagedObject], toModelClass modelClass: T.Type) -> ([T], [NSError?]) {

        var transformed: [T] = []
        var errors: [NSError?] = []

        for result in results {
            var error: NSError? = nil
            var model: T = MTLManagedObjectAdapter.modelOfClass(modelClass, fromManagedObject: result, error: &error) as T
            transformed.append(model)
            errors.append(error)
        }

        return (transformed, errors)
    }
}

You can call this method like:

let (transformed, errors) = Mapper.mapResults(results, toModelClass: MyModel.self)

Moreover, according to MTLManagedObjectAdapter.h,

// modelClass    - The MTLModel subclass to return. This class must conform to
//                 <MTLManagedObjectSerializing>. This argument must not be nil.

So you should restrict T as MTLModel and conforms to MTLManagedObjectSerializing:

class func mapResults<T: MTLModel where T: MTLManagedObjectSerializing>(results: [NSManagedObject], toModelClass modelClass: T.Type) -> ([T], [NSError?]) {
Sign up to request clarification or add additional context in comments.

1 Comment

This is fantastic, I had completely forgotten about generics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.