Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27159

Core Data optional attributes and properties with Swift rules

Swift introduced good opportunity for developers by adding optionals, but now when I use Core Data I have few issues.

I use API which returns form the server some objects which I want to map to appropriate Core Data objects and then create records.

For example I have id, name, age properties and these are all non optional properties that I receive from the server.

In an another hand we may be at situation when server return for us for some property. But let's say this was happen for id property somehow.

My question is do we need to have optional or non optional properties how to determine which one to use. Currently all my properties are optionals and it's annoying to unwrap it everywhere. Maybe it's better to create validator and prevent insert any null objects.

Upvotes: 2

Views: 586

Answers (1)

Jerry Krinock
Jerry Krinock

Reputation: 5030

I think that if the Swift team at Apple would read your question, they would smile and say: "Good question! Another example of how Swift is helping developers to question and improve their code."

My approach to this is:

  1. Let Core Data be Core Data. Attributes can be null. If proper operation requires an attribute to be not null, you may wish to validate this prior to insertion. But, since Core Data is a persistence framework, I assume that these objects are being saved to the disk, and data from the disk should never be trusted … it could be corrupt, or some unforseen future version of your app or an app extension could either intentionally or unintentionally cause some attributes to be null.

  2. Let Swift be Swift. A major design goal of Swift was to protect you from such unexpected nulls. As you have recognized, force unwrapping is discouraged. Instead, use if let or guard let. These are explained in Apple's Swift book, although you can find dozens of blog posts like this one which are more to the point.

Upvotes: 3

Related Questions