@FreezeSchema
The@FreezeSchema macro marks a SwiftData VersionedSchema for freezing and generates helper functions for freezing and drift detection.
Overview
@FreezeSchema is an attached macro that generates two static functions:
__freezeray_freeze_X_Y_Z()- Exports the schema to SQLite fixtures__freezeray_check_X_Y_Z()- Validates the schema hasn’t drifted from the frozen version
Declaration
Parameters
version
Type: String
Required: Yes
The version identifier for this schema. Used to organize fixtures in FreezeRay/Fixtures/<VERSION>/.
Format: Any string, but semantic versioning is recommended:
"1.0.0"- Full semantic version"1","2"- Simple incremental"2024-01-15"- Date-based
The
version string is separate from SwiftData’s versionIdentifier. Use it to organize your frozen fixtures.Usage
Basic Example
Multiple Schema Versions
Generated Code
When you add@FreezeSchema(version: "1.0.0") to a schema, the macro generates:
Freeze Function
- FreezeRay CLI during
freezeray freeze 1.0.0 - Temporary test generated by CLI
- Creates a ModelContainer with the schema
- Generates a SQLite database in iOS Simulator
- Exports fixtures to
/tmp/FreezeRay/Fixtures/1.0.0/ - CLI copies fixtures to your project
Drift Check Function
- Scaffolded drift tests
- Your test suite (on every run)
- Loads frozen fixtures from
FreezeRay/Fixtures/1.0.0/ - Generates current schema and computes checksum
- Compares current checksum with frozen checksum
- Throws
FreezeRayError.schemaDriftif they don’t match
Function Naming
The generated function names use underscores instead of dots:The double underscore prefix (
__) indicates these are internal functions not meant for direct use.Availability
Both generated functions are marked with:Requirements
Must Be Applied to Enum
Must Have Version Parameter
Must Conform to VersionedSchema
How It Works
Macro Expansion
The macro is aMemberMacro that adds members (functions) to the schema enum.
Before macro expansion:
Runtime Integration
The generated functions callFreezeRayRuntime methods:
Common Use Cases
Freezing Multiple Schemas
Annotate each schema version:Version Naming Strategies
Semantic Versioning (Recommended):Schema Organization
Option 1: One file per versionDebugging Macro Expansion
To see the expanded code, use Xcode’s macro expansion tool:- Right-click on
@FreezeSchema - Select Expand Macro
- View the generated code inline
-print-expanded-macro flag:
Error Messages
Invalid Version Argument
Not Applied to Enum
Best Practices
1. Annotate All Schema Versions
2. Use Consistent Version Format
3. Freeze Before Shipping
Add@FreezeSchema before releasing to production:
4. Keep Annotations After Freezing
Related
freeze command
CLI command that calls the freeze function
Schema Freezing
Learn how schema freezing works
Drift Detection
How drift check functions detect changes
First Freeze Guide
Tutorial for using @FreezeSchema