swiftcore-data

Is it ok to make a CoreData entity Identifiable?


I am new to CoreData but I made an object that I intend to use an array of within a ForEach loop in SwiftUI.

In the entity editor I added a UUID attribute stored_id. Then in an extension I wrote this:

extension Item: Identifiable {
    public var id: UUID {
        guard let stored_id else {
            assertionFailure("No stored ID")
            return UUID()
        }
        return stored_id
    }
    
}

This just feels pretty strange to me for multiple reasons like the fact that stored_id is optional given CoreDatas semantics. Is this bad practice for some reason.


Solution

  • You can have Core Data entities conform to Identifiable, and indeed if you create a new Core Data project today (and I believe since Xcode 14) then the Identifiable conformance is already added when the entity class is created:

    This is the code that was generated by simply creating a new app with Core Data storage in Xcode 16:

    extension Item {
    
        @nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
            return NSFetchRequest<Item>(entityName: "Item")
        }
    
        @NSManaged public var timestamp: Date?
    
    }
    
    extension Item : Identifiable {
    
    }
    

    If you do want/need to add conformance yourself then there is no need for an additional property. You can leverage the in-built identity of a NSManagedObject subclass simply by adding it as the boilerplate does.

    extension Item : Identifiable {}