Skip to content

dynamicInitialValue support for @Field.Stored and @Field.Coded properties

Compare
Choose a tag to compare
@JohnEstropia JohnEstropia released this 20 Jun 08:48
· 112 commits to develop since this release
e720504

Default values vs. Initial values

One common mistake when assigning default values to CoreStoreObject properties is to assign it a value and expect it to be evaluated whenever an object is created:

// ❌
class Person: CoreStoreObject {

    @Field.Stored("identifier")
    var identifier: UUID = UUID() // Wrong!
    
    @Field.Stored("createdDate")
    var createdDate: Date = Date() // Wrong!
}

This default value will be evaluated only when the DataStack sets up the schema, and all instances will end up having the same values. This syntax for "default values" are usually used only for actual reasonable constant values, or sentinel values such as "" or 0.

For actual "initial values", @Field.Stored and @Field.Coded now supports dynamic evaluation during object creation via the dynamicInitialValue: argument:

// ✅
class Person: CoreStoreObject {

    @Field.Stored("identifier", dynamicInitialValue: { UUID() })
    var identifier: UUID
    
    @Field.Stored("createdDate", dynamicInitialValue: { Date() })
    var createdDate: Date
}

When using this feature, a "default value" should not be assigned (i.e. no = expression).