Core data | automatically generated String and Date attributes are optional even when not marked in swift

I have noticed the date and string attributes are always created as optionals in swift in auto-generated classes even when optional attribute is not selected.

In the apple documentation also, all Date and string are shown as optional in example

In Swift, you declare the properties using the @NSManaged keyword:

class MyManagedObject: NSManagedObject {

}

Currently using swift 3.2 I dont want certain string attributes to be non- optional. How do I fix this?

Replies

“Optional” for Core Data doesn’t mean the same thing that it does for Swift.


Because of now CoreData is implemented, attribute values can be null at unexpected times, or during initialization before you’ve assigned a value to that attribute, and that fact mandates using Swift’s optional declaration.

Feel free to manually adjust the type yourself, so that it's not an optional. Just delete the `?`. It may crash at runtime if you try to access it when it's nil, so be carefull.


You might want to do this, if your core data model has assigned a default value for the attribute.