Skip to content

Support SwiftData models #398

Description

@Pedrexus

Hello all, thanks for the nice project.

Is your feature request related to a problem? Please describe.

JSONSchemaConvertible doesn't work with SwiftData @Model classes. Calling derivedJsonSchema() throws JSONSchemaConvertationError.typeUnsupported at runtime:

@Model
final class DictionaryEntry: Codable {
    var input: String = ""
    var entries: [Entry] = []
}

extension DictionaryEntry: JSONSchemaConvertible {
    static var example: DictionaryEntry { /* ... */ }
}

// Throws typeUnsupported
let schema = JSONSchema.derivedJsonSchema(DictionaryEntry.self)

Describe the solution you'd like

I believe the root cause is that PropertyValue.init(from:) uses Mirror to reflect the example instance. For @Model classes, Mirror sees internal SwiftData properties (injected by the macro) that have unsupported types. Probably the solution could be to filter out properties starting with _ or $, use some enum to determine which properties to include or at least document this limitation.

Describe alternatives you've considered

Creating plain structs that duplicate the model structure:

struct DictionaryEntryDTO: Codable, JSONSchemaConvertible {
    let input: String
    let entries: [EntryDTO]
    static var example: Self { /* ... */ }
}

let schema = JSONSchema.derivedJsonSchema(DictionaryEntryDTO.self)

The above works but I need to maintain duplicate types.

Additional context

  • SwiftData @Model macro synthesizes properties for observation/persistence
  • These are visible to Mirror but not part of Codable
  • Tested with v0.4.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions