aryaxt aryaxt - 5 months ago 126
Swift Question

Swift initialize Self in a static methods

Having problem getting this to work, inside User.provideInstance I'm unable to initialize Self and return. Any thoughts?

extension NSManagedObject {
public convenience init(managedObjectContext: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName(String(self.dynamicType), inManagedObjectContext: managedObjectContext)!
self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
}
}

public protocol Deserializable {
static func provideInstance(json: [NSObject: AnyObject]) -> Self
}

@objc(User) public class User: NSManagedObject, Deserializable {

public static func provideInstance(json: [NSObject: AnyObject]) -> Self {
let context = DIContainer.instance.resolve(CoreDataStack.self).managedObjectContext
let instance = self.init(managedObjectContext: context)
return instance
}
}


Error is on
let instance = self.init(managedObjectContext: context)
:


Constructing an object of class type Self with a metatype value must use a required initializer

Answer

Why bother with initializers?

extension NSManagedObject {
    class func provide(managedObjectContext managedObjectContext: NSManagedObjectContext) -> Self {
        let entity = NSEntityDescription.entityForName(String(self.dynamicType), inManagedObjectContext: managedObjectContext)!
        return self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
    }
}

public protocol Deserializable {
    static func provideInstance(json: [NSObject: AnyObject]) -> Self
}

@objc(User) public class User: NSManagedObject, Deserializable {

    public static func provideInstance(json: [NSObject: AnyObject]) -> Self {
        let context = ...
        let instance = self.provide(managedObjectContext: context)
        return instance
    }
}

The problem with initializers is that they are not always inherited, unless they are required. And you cannot create a required initializer in an extension.