barndog
barndog

Reputation: 7163

Swift Declared Typed Array from AnyClass object

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?

Upvotes: 0

Views: 551

Answers (1)

rintaro
rintaro

Reputation: 51911

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?]) {

Upvotes: 2

Related Questions