Can't assign yourself in a method - Swift
In Xcode 6.1 and with the blog post on Failover Initializers on the Swift Blog, Apple assigned itself to a failover initializer.
The Int (fromString :)) example on the blog compiles fine when copied to my project with an assignment to self, but trying to do this with a custom class in my own code results in the usual "Cannot assign 'self' in method" error.
extension Contact {
public convenience init?(context: NSManagedObjectContext = DataStore.managedObjectContext) {
if let userId = User.loggedInUserId(context) {
let contact = NSEntityDescription.insertNewObjectForEntityForName("Contact", inManagedObjectContext: context) as Contact
self = contact
} else {
return nil
}
}
}
(Contact is a subclass of NSManagedObject)
Is there anything I can't see with error initializers?
source to share
The assignmentself
applies only to value types, struct
and enum
.
In your case, you should do the following:
public convenience init?(context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Contact", inManagedObjectContext: context);
self.init(entity: entity!, insertIntoManagedObjectContext: context)
if User.loggedInUserId(context) == nil {
context.deleteObject(self)
return nil
}
}
You must call unconditionally self.init(..)
, because that is the rule for an initializer convenience
. If condition false
, deleteObject(self)
and return nil
. Hmm ... I guess you shouldn't use initializers for this.
source to share