DEV Community


Day 57 of 100 Days of SwiftUI

Oluwasanmi Aderibigbe
Android developer
・1 min read

I just completed day 57 of 100 days of SwiftUI. Today I learnt more about CoreData. I learnt how to create CoreData models without optional, how to ensure the uniqueness of your models using constraints and the conditional saving of NSNSManagedObjectContext.

By default, properties of models created by CoreData are optional. To make them non-optional, you have to opt out of code-gen. You can do this by selecting the code-gen manual/none option and creating an NSManagedObject subclass.
Alt Text
This will create to two classes for you. Person+CoreDataProperties.swift and Person+CoreDataClass.swift (Person is the name of my model)

extension Person {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Person> {
        return NSFetchRequest<Person>(entityName: "Person")

    @NSManaged public var name: String?

    public var wrappedName: String {
        name ?? "Unknown Name"

extension Person : Identifiable {

Enter fullscreen mode Exit fullscreen mode

The code above is an NSManagedObject subclass. It has an optional property called name. In order to make that property non-optional, we simply created a computed property called wrappedName.

In order to make your data unique, all you have to do is add this line of code to the willConnectTo method in the SceneDelegate.swift directly below the code that starts with let context

context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
Enter fullscreen mode Exit fullscreen mode

Discussion (0)