2
votes

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 {

@NSManaged var title: String?

@NSManaged var date: NSDate?

}

Currently using swift 3.2 I dont want certain string attributes to be non- optional. What is the best way to make it as mandatory?

2

2 Answers

1
votes

Two options

  • Edit the MyManagedObject to make them non-optional. This means you need to maintain this class yourself and do any changes both in the core data model and the class
  • Create a protocol (or sub class) with same attributes (you need to give them new names) but non-optional and implement this protocol in a separate extension to get and set original attributes and then use this protocol rather than MyManagedObject in your code.

If your data model is stable and won't be changed that much the first option is probably best.

0
votes

When the entities will be fetched from core data, some of the properties of that entity may not have any value associated with them and they will be nil. That is why it make sense to have the core data properties as an optional.

Similarly, for an example, if you try to fetch the value of any key from a Dictionary in Swift, the value is always an optional as we may or may not have that key in the Dictionary. So, every time any property could be nil, make it optional.