NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Default Core Data entity value with static var property?

Forums > SwiftUI

I have a score property on my Core Data Entity Student. So, when adding a newStudent object, its related one-to-one score property must have a value, different from nil, to be saved.

User can change that score value later on another views, but for object creation itself I do need a default value. And I can't find a working way to set a default one.

My Student class:

extension Student {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Student> {
        return NSFetchRequest<Student>(entityName: "Student")
    //Another properties...
    @NSManaged public var evaluation: Score?

My Score class:

extension Score {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Score> {
        return NSFetchRequest<Score>(entityName: "Score")
    //Another properties...
    @NSManaged public var depiction: String?
    @NSManaged public var student: Student?

I suposse I have to create any type of singleton, and static var not to be created-and-saved each time I add a student, but just to pass it to the ViewContext to be saved as a part of newStudent saving. I hope I have explained myself...

I'm trying to add something like this to my Students+CoreDataMethods:

extension Score {
    static var defaultScore: Score {
        self.defaultScore.depiction = "None"

But it throws errors like "Function call causes an infinite recursion", and "Missing return in getter expected to return 'Score'"".

I don't find a correct approach to deal with it. Any ideas? Thanks!


When you create a Core Data entity in the model editor, you can indicate a default value for each property.

For example:

default value in Core Data model editor

This will cause the depiction property to have a default value of "None" whenever a new Score is created.



Yes: it gives the value "None" for "score" property when a new "Score" is created.

But what I need is giving this "None" value to Students's "score" property, when a "Student" is created, to this property:



Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.