Reputation: 24912
If I try to add a stored property to a subclass in NSManagedObject
in Swift, without providing it with a default value (I'll do that in an initialiser, mind you), I get this error:
Stored property 'foo' requires an initial value or should be @NSManaged
The code is as follows:
class Thing : NSManagedObject{
var foo : String
var bar : String
init(foo: String, bar : String){
// blah, blah...
}
}
What's the reason for enforcing this? Why the heck can't I initialise in an initialiser????
Upvotes: 1
Views: 1348
Reputation: 299345
EDIT: The below answer applies to a wide variety of situations, and is related for this, but does not exactly address the NSManagedObject
situation. In the case of NSManagedObject
, an object can be loaded from the persistent store and initialized without calling your special init. Swift doesn't know what it should assign foo
and bar
in those cases, so requires some default values (rather than just using final
or required
as you could do in other subclassing situations cases).
So the correct question is: what would you expect Core Data to do with foo
and bar
when it loads this object out of the data store?
Because the compiler cannot prove that all subclasses will implement or call init(foo,bar)
. If a subclass did not implement that initializer, then foo
or bar
may not be initialized.
You can resolve this many ways. You can provide defaults. You can make the values explicitly unwrapped optionals (making their default nil
). You can make the values optional. You can declare this initializer required
so that all subclasses must implement it. Or you can declare Thing
to be final
so that it cannot be subclassed.
Upvotes: 5