Search code examples
swiftuicore-dataswiftdata

SwiftData: Is using Model().id is fine or is it necessary to make a model attribute unique?


A beginner here

I have seen that a SwiftData model has an id property which is a PersistentIdentifier. https://developer.apple.com/documentation/swiftdata/persistentidentifier

Currently I don't use an id (UUID) property for my model nor I have made an attribute unique.

Does the persistentIdentifier make the model unique?

Like let itemA = Item() and let itemB = Item() itemA.id and itemB.id be sufficient or is it good to make an attribute unique?

Will it cause a problem while migrating or even using CloudKit by creating a new property uniqueID = UUID() or making a property unique?

Is it just fine to use Item().id as the identifier?

I am confused to understand it.

EDIT 2: I tried to add an Attribute Unique to an existing property I didn't find any crash. But I am still unsure.


Solution

  • A PersistentModel has a unique identifier persistentModelID that in itself contains a unique identifier for the model in its store.

    PersistentModel extends Identifiable and uses persistentModelID as the id for conforming to Identifiable. This is done in an extension and you can override it with your own unique property instead like a UUID property.

    You need to be aware though that if you do this the model class will have two unique identifiers and depend ending on what you want to do in your code you might need to use one or the other.

    One example is the ModelContext function model(for:) that requires a PersistentIdentifier so doing context.model(for: myModel.id) will no longer work with a custom id property. This is a simple example since the compiler will tell you when you are doing it wrong but there might be other scenarios where one need to be more careful with which identifier to use.


    Some notes:

    I am personally avoiding to implement custom id properties for now and prefer to use the default implementation.

    I haven't start using CloudKit with SwiftData yet myself but I haven't read anything about any issues with using a custom identifier

    The unique attribute that can be set on a property is something different and not directly related to this.