### Initializing a SwiftData Schema Source: https://developer.apple.com/documentation/swiftdata/versionedschema Provides examples of how to initialize a SwiftData schema, either directly with schema entities and a version, or by using a convenience initializer with a versioned schema type. These initializers are key to setting up your data model. ```swift init(Schema.Entity..., version: Schema.Version) init([any PersistentModel.Type], version: Schema.Version) convenience init(versionedSchema: any VersionedSchema.Type) init() ``` -------------------------------- ### Basic FetchDescriptor with Predicate and Sort Order Source: https://developer.apple.com/documentation/swiftdata/fetchdescriptor Create a FetchDescriptor to retrieve specific models, filtering by a predicate and sorting by a creation date. This example limits the fetch to 10 results. ```swift let descriptor = FetchDescriptor( predicate: #Predicate { $0.isFavorite == true }, sortBy: [ .init(\.createdAt) ] ) descriptor.fetchLimit = 10 let favoriteRecipes = try modelContext.fetch(descriptor) ``` -------------------------------- ### Use Query in a SwiftUI View Source: https://developer.apple.com/documentation/swiftdata/query/init%28filter%3Asort%3Aorder%3Atransaction%3A%29-8q7vs An example demonstrating how to use the @Query property wrapper within a SwiftUI view to fetch and display a list of recipes sorted by their creation date. ```swift struct RecipeList: View { // Recipes sorted by date of creation @Query(sort: \.dateCreated) var favoriteRecipes: [Recipe] var body: some View { List(favoriteRecipes) { RecipeDetails($0) } } } ``` -------------------------------- ### Define DataStoreConfiguration Protocol Source: https://developer.apple.com/documentation/swiftdata/datastoreconfiguration This snippet illustrates the protocol definition for DataStoreConfiguration, which inherits from Hashable and requires specific properties and methods for data store setup. ```swift protocol DataStoreConfiguration : Hashable { associatedtype Store : DataStore var name: String { get } var schema: Schema? { get } func validate() throws } ``` -------------------------------- ### init(_:_:_:) Source: https://developer.apple.com/documentation/swiftdata/schema/version-swift.struct/init%28_%3A_%3A_%3A%29 Initializes a new Schema.Version instance with semantic versioning components. ```APIDOC ## init(_:_:_:) ### Description Initializes a version struct with the provided components of a semantic version. ### Method Initializer ### Parameters #### Path Parameters - **major** (Int) - Required - The major version number. Must be >= 0. - **minor** (Int) - Required - The minor version number. Must be >= 0. - **patch** (Int) - Required - The patch version number. Must be >= 0. ### Request Example Schema.Version(1, 0, 0) ### Response #### Success Response (200) - **Schema.Version** (Object) - A new instance of the version struct. ``` -------------------------------- ### Example SwiftData Model Relationships Source: https://developer.apple.com/documentation/swiftdata/relationship%28_%3Adeleterule%3Aminimummodelcount%3Amaximummodelcount%3Aoriginalname%3Ainverse%3Ahashmodifier%3A%29 Demonstrates how to use the @Relationship macro to define relationships between SwiftData models. This example shows a one-to-many relationship between a Category and multiple RemoteImage models, including the inverse relationship. ```swift @Model class RemoteImage { @Attribute(.unique) var sourceURL: URL @Relationship(inverse: \Category.images) var category: Category? var data: Data init(sourceURL: URL, data: Data = Data()) { self.sourceURL = sourceURL self.data = data } } @Model class Category { @Attribute(.unique) var name: String @Relationship var images = [RemoteImage]() init(name: String) { self.name = name } } ``` -------------------------------- ### Creating a Schema Source: https://developer.apple.com/documentation/swiftdata/schema Demonstrates how to create a SwiftData Schema using various initializers. ```APIDOC ## Creating a schema ### Initializers * `init(Schema.Entity..., version: Schema.Version)` * `init([any PersistentModel.Type], version: Schema.Version)` * `convenience init(versionedSchema: any VersionedSchema.Type)` * `convenience init(any PersistentModel.Type..., version: Schema.Version)` ``` -------------------------------- ### GET /DataStoreFetchRequest/descriptor Source: https://developer.apple.com/documentation/swiftdata/datastorefetchrequest/descriptor Retrieves the FetchDescriptor associated with a DataStoreFetchRequest instance. ```APIDOC ## GET /DataStoreFetchRequest/descriptor ### Description Returns the fetch descriptor that defines the criteria, sorting, and configuration for a data fetch operation in SwiftData. ### Method GET ### Endpoint /DataStoreFetchRequest/descriptor ### Parameters #### Path Parameters - None #### Query Parameters - None ### Request Example GET /DataStoreFetchRequest/descriptor ### Response #### Success Response (200) - **descriptor** (FetchDescriptor) - The configuration object defining the fetch request. #### Response Example { "descriptor": { "predicate": null, "sortBy": [], "fetchLimit": 0 } } ``` -------------------------------- ### SwiftData Model Container Initialization (Throws) Source: https://developer.apple.com/documentation/swiftdata/persistentmodel Demonstrates initializers for creating a model container. These methods allow for the configuration of the data store, including specifying the schema, migration plan, and other configurations. ```swift init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws convenience init(for: any PersistentModel.Type..., migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) convenience init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) ``` -------------------------------- ### GET DataStoreConfiguration.name Source: https://developer.apple.com/documentation/swiftdata/datastoreconfiguration/name Retrieves the name property of a DataStoreConfiguration instance. ```APIDOC ## GET DataStoreConfiguration.name ### Description Retrieves the unique name associated with the DataStoreConfiguration instance. ### Method GET ### Endpoint DataStoreConfiguration.name ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **name** (String) - The identifier string for the configuration. #### Response Example { "name": "primary-store" } ``` -------------------------------- ### Access Entity Name Source: https://developer.apple.com/documentation/swiftdata/persistentidentifier Gets the entity name for the associated model. ```swift var entityName: String ``` -------------------------------- ### Initializer: init(_:) Source: https://developer.apple.com/documentation/swiftdata/schema/index/init%28_%3A%29-527in Initializes a new index for a SwiftData schema using a variadic list of key paths. ```APIDOC ## init(_:) ### Description Creates a new index for a model schema using the provided key paths. ### Method Initializer ### Endpoint Schema.Index.init(_ binaryIndices: [PartialKeyPath]...) ### Parameters #### Path Parameters - **binaryIndices** (Array>) - Required - A variadic list of key paths representing the properties to include in the index. ### Request Example let index = Schema.Index(\User.username, \User.email) ### Response #### Success Response (N/A) - **Schema.Index** - An initialized index object for the specified model properties. ``` -------------------------------- ### GET schemaMetadata Source: https://developer.apple.com/documentation/swiftdata/persistentmodel/schemametadata Retrieves the schema metadata for a persistent model in SwiftData. ```APIDOC ## GET schemaMetadata ### Description Returns the metadata for the properties defined within a persistent model's schema. ### Method GET ### Endpoint /schemaMetadata ### Parameters #### Path Parameters - None #### Query Parameters - None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **schemaMetadata** ([Schema.PropertyMetadata]) - An array containing the metadata for each property in the schema. #### Response Example { "schemaMetadata": [ { "name": "id", "type": "UUID" }, { "name": "name", "type": "String" } ] } ``` -------------------------------- ### GET /HistoryTransaction/timestamp Source: https://developer.apple.com/documentation/swiftdata/historytransaction/timestamp Retrieves the timestamp property from a HistoryTransaction instance in SwiftData. ```APIDOC ## GET /HistoryTransaction/timestamp ### Description Returns the date and time at which the transaction occurred. ### Method GET ### Endpoint HistoryTransaction.timestamp ### Parameters #### Path Parameters - **None** ### Request Example N/A (Instance Property Access) ### Response #### Success Response (200) - **timestamp** (Date) - The date object representing the transaction time. #### Response Example { "timestamp": "2023-10-27T10:00:00Z" } ``` -------------------------------- ### init(for:migrationPlan:configurations:) Source: https://developer.apple.com/documentation/swiftdata/modelcontainer/init%28for%3Amigrationplan%3Aconfigurations%3A%29-1czix Initializes a new ModelContainer instance with a defined schema, optional migration plan, and model configurations. ```APIDOC ## Initializer: init(for:migrationPlan:configurations:) ### Description Creates a model container using the specified schema, migration plan, and configurations to manage persistent storage. ### Method Initializer ### Parameters #### Parameters - **givenSchema** (Schema) - Required - A schema that maps your app’s model classes to the associated data in the app’s persistent storage. - **migrationPlan** ((any SchemaMigrationPlan.Type)?) - Optional - A plan that describes the evolution of your app’s schema and how the container migrates between versions. - **configurations** ([ModelConfiguration]) - Required - An array of configurations that describe how the container manages the persisted data for specific groups of models. ### Request Example ```swift let container = try ModelContainer( for: mySchema, migrationPlan: MyMigrationPlan.self, configurations: [ModelConfiguration(isStoredInMemoryOnly: false)] ) ``` ### Response #### Success Response - **ModelContainer** (Instance) - Returns an initialized ModelContainer instance. #### Error Handling - Throws an error if the container cannot be created, such as when configuration requirements are not met. ``` -------------------------------- ### GET processIdentifier Source: https://developer.apple.com/documentation/swiftdata/defaulthistorytransaction/processidentifier Access the process identifier associated with a DefaultHistoryTransaction instance. ```APIDOC ## GET processIdentifier ### Description Retrieves the unique identifier for the process that generated the history transaction. ### Method Property Access ### Endpoint DefaultHistoryTransaction.processIdentifier ### Parameters None ### Request Example let transaction: DefaultHistoryTransaction = ... let id = transaction.processIdentifier ### Response #### Success Response (200) - **processIdentifier** (String) - The unique identifier of the process. #### Response Example "com.apple.example.app" ``` -------------------------------- ### Initialize Query with Predicate, Non-Optional KeyPath Sort, and Animation Source: https://developer.apple.com/documentation/swiftdata/query Creates a query with a Predicate, sorting by a non-optional property using a KeyPath, and an Animation. ```swift init(filter: Predicate?, sort: KeyPath, order: SortOrder, animation: Animation) ``` -------------------------------- ### init(_:animation:sectionBy:) Source: https://developer.apple.com/documentation/swiftdata/query/init%28_%3Aanimation%3Asectionby%3A%29-2em2m Creates a sectioned query from a fetch descriptor, grouped into sections by a String key path. This initializer is available for elements conforming to `PersistentModel` and is marked as Beta. ```APIDOC ## init(_:animation:sectionBy:) ### Description Creates a sectioned query from a fetch descriptor, grouped into sections by a String key path. ### Method `init` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift @MainActor @preconcurrency init( _ descriptor: FetchDescriptor, animation: Animation, sectionBy sectionKeyPath: KeyPath? = nil ) where Result == [Element] ``` ### Response #### Success Response Returns a sectioned query. #### Response Example None explicitly provided, but the initializer returns a `[Element]` where `Element` conforms to `PersistentModel`. ``` -------------------------------- ### GET Schema.Entity.attributes Source: https://developer.apple.com/documentation/swiftdata/schema/entity/attributes Retrieves the set of attributes defined for a specific SwiftData entity. ```APIDOC ## GET Schema.Entity.attributes ### Description Accesses the collection of attributes defined within a SwiftData entity schema. ### Method GET ### Endpoint Schema.Entity.attributes ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **attributes** (Set) - A set containing all attribute definitions for the entity. #### Response Example { "attributes": [ { "name": "id", "type": "UUID" }, { "name": "name", "type": "String" } ] } ``` -------------------------------- ### Get Persistent Model ID Source: https://developer.apple.com/documentation/swiftdata/persistentidentifier Accesses the PersistentIdentifier associated with a model instance. ```swift var persistentModelID: PersistentIdentifier ``` -------------------------------- ### Initialize Query with Predicate, Sort Descriptors, and Animation Source: https://developer.apple.com/documentation/swiftdata/query Creates a query with a Predicate for filtering and a list of SortDescriptors for ordering, along with an Animation. ```swift init(filter: Predicate?, sort: [SortDescriptor], animation: Animation) ``` -------------------------------- ### GET changeIdentifier Source: https://developer.apple.com/documentation/swiftdata/historyupdate/changeidentifier-swift.property Retrieves the unique change identifier for a HistoryUpdate instance in SwiftData. ```APIDOC ## GET changeIdentifier ### Description Returns the unique identifier associated with a specific change event within the SwiftData history tracking system. ### Method GET ### Endpoint HistoryUpdate.changeIdentifier ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **changeIdentifier** (Self.ChangeIdentifier) - The unique identifier for the change. #### Response Example { "changeIdentifier": "UUID-STRING-1234-5678" } ``` -------------------------------- ### init(name:originalName:options:valueType:defaultValue:hashModifier:) Source: https://developer.apple.com/documentation/swiftdata/schema/attribute/init%28name%3Aoriginalname%3Aoptions%3Avaluetype%3Adefaultvalue%3Ahashmodifier%3A%29 Initializes a new schema attribute with the specified configuration options. ```APIDOC ## SwiftData Schema.Attribute Initializer ### Description Creates a new attribute definition for a SwiftData schema, allowing for configuration of naming, constraints, and default values. ### Method Initializer ### Endpoint Schema.Attribute.init(name:originalName:options:valueType:defaultValue:hashModifier:) ### Parameters #### Parameters - **name** (String) - Required - The name of the attribute. - **originalName** (String?) - Optional - The original name of the attribute for migration purposes. - **options** ([Schema.Attribute.Option]) - Optional - An array of configuration options for the attribute. - **valueType** (any Any.Type) - Required - The Swift type of the attribute. - **defaultValue** (Any?) - Optional - The default value for the attribute. - **hashModifier** (String?) - Optional - A string used to modify the hash of the attribute. ### Request Example ```swift Schema.Attribute( name: "username", valueType: String.self, defaultValue: "Guest" ) ``` ### Response #### Success Response - **Schema.Attribute** - Returns an initialized attribute instance. ``` -------------------------------- ### Initialize Query with Predicate, KeyPath Sort, and Animation Source: https://developer.apple.com/documentation/swiftdata/query Creates a query with a Predicate, sorting by a specific property using a KeyPath, and an Animation. Supports optional property values. ```swift init(filter: Predicate?, sort: KeyPath, order: SortOrder, animation: Animation) ``` -------------------------------- ### GET changedPersistentIdentifier Source: https://developer.apple.com/documentation/swiftdata/historyinsert/changedpersistentidentifier Retrieves the persistent identifier associated with a change in a SwiftData model. ```APIDOC ## GET changedPersistentIdentifier ### Description Returns the current persistent identifier for a model instance that has undergone a change. ### Method GET ### Endpoint /swiftdata/changedPersistentIdentifier ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **changedPersistentIdentifier** (PersistentIdentifier) - The unique identifier for the changed object. #### Response Example { "changedPersistentIdentifier": "x-coredata://..." } ``` -------------------------------- ### GET bundleIdentifier Property Source: https://developer.apple.com/documentation/swiftdata/defaulthistorytransaction/bundleidentifier Retrieves the bundle identifier associated with a DefaultHistoryTransaction instance. ```APIDOC ## GET bundleIdentifier ### Description Returns the unique bundle identifier string associated with the specific history transaction. ### Method Property Access (Swift) ### Endpoint DefaultHistoryTransaction.bundleIdentifier ### Parameters None ### Request Example let identifier = transaction.bundleIdentifier ### Response #### Success Response (String) - **bundleIdentifier** (String) - The unique identifier of the bundle that originated the transaction. #### Response Example "com.example.myapp" ``` -------------------------------- ### Initialize ModelContainer with Schema Source: https://developer.apple.com/documentation/swiftdata/modelcontainer Demonstrates initializing a ModelContainer with a specific Schema, an optional migration plan, and an array of ModelConfiguration objects. This allows for fine-grained control over storage and migration. ```swift init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws ``` -------------------------------- ### Use Query in a SwiftUI View Source: https://developer.apple.com/documentation/swiftdata/query/init%28filter%3Asort%3Aanimation%3A%29 Demonstrates how to use the @Query property wrapper within a SwiftUI view to fetch and display filtered and sorted data. The example filters for favorite recipes and sorts them by creation date. ```swift struct RecipeList: View { @Query( filter: #Predicate { $0.isFavorite == true }, sort: [SortDescriptor(\.dateCreated)] ) var favoriteRecipes: [Recipe] var body: some View { List(favoriteRecipes) { RecipeDetails($0) } } } ``` -------------------------------- ### init(predicate:sortBy:) Source: https://developer.apple.com/documentation/swiftdata/fetchdescriptor/init%28predicate%3Asortby%3A%29 Initializes a new fetch descriptor with optional filtering and sorting criteria. ```APIDOC ## INIT init(predicate:sortBy:) ### Description Creates a fetch descriptor with the specified predicate that, optionally, arranges the fetched models in a particular order. ### Method Initializer ### Endpoint init(predicate: Predicate? = nil, sortBy: [SortDescriptor] = []) ### Parameters #### Path Parameters - **predicate** (Predicate?) - Optional - The logical condition that determines whether the fetch includes a specific model in its results. Default is nil. - **sortBy** ([SortDescriptor]) - Optional - The array of sort descriptors that tell the fetch how to order its results. Default is an empty array. ### Request Example let descriptor = FetchDescriptor(predicate: #Predicate { $0.name == "John" }, sortBy: [SortDescriptor(\.name)]) ### Response #### Success Response (Instance) - **FetchDescriptor** - Returns a configured fetch descriptor instance. ``` -------------------------------- ### GET metadata property Source: https://developer.apple.com/documentation/swiftdata/backingdata/metadata Accesses the metadata property of a BackingData instance in SwiftData. ```APIDOC ## GET metadata ### Description Retrieves the metadata associated with a BackingData instance. This property provides access to the underlying storage information for a persistent model. ### Method GET ### Endpoint BackingData.metadata ### Parameters #### Path Parameters - None ### Request Example N/A (Instance property access) ### Response #### Success Response (200) - **metadata** (Any) - The metadata object associated with the backing data. #### Response Example { "metadata": "[Metadata Object]" } ``` -------------------------------- ### Initialize Query with Predicate, Optional KeyPath Sort, and Transaction Source: https://developer.apple.com/documentation/swiftdata/query Creates a query with a Predicate, sorting by an optional property using a KeyPath, and a Transaction. ```swift init(filter: Predicate?, sort: KeyPath, order: SortOrder, transaction: Transaction?) ``` -------------------------------- ### Getting query configuration Source: https://developer.apple.com/documentation/swiftdata/query Accesses the model context and any fetch errors associated with the query. ```APIDOC ## `var modelContext: ModelContext` ### Description Provides access to the `ModelContext` that the `Query` interacts with. ### Parameters None ### Response - **modelContext** (ModelContext) - The current model context. ``` ```APIDOC ## `var fetchError: (any Error)?` ### Description Retrieves any error encountered during the most recent attempt to fetch data for the query. ### Parameters None ### Response - **fetchError** ((any Error)?) - An optional error object if a fetch error occurred. ``` -------------------------------- ### GET /SchemaProperty/isTransient Source: https://developer.apple.com/documentation/swiftdata/schemaproperty/istransient Access the isTransient property to determine if a schema property should be excluded from persistence. ```APIDOC ## Property: isTransient ### Description A Boolean value that indicates whether the property is transient. Transient properties are not persisted in the underlying data store. ### Type Boolean ### Availability - iOS 17.0+ - macOS 14.0+ - Swift 5.9+ ### Declaration `var isTransient: Bool { get }` ### Usage Access this property on a `SchemaProperty` instance to check if the field is marked for exclusion from the database schema. ### Response Example { "isTransient": false } ``` -------------------------------- ### DefaultStore Class Overview Source: https://developer.apple.com/documentation/SwiftData/DefaultStore Overview of the DefaultStore class, its properties, and protocol conformances. ```APIDOC ## Class: DefaultStore ### Description A data store that uses Core Data as its underlying storage mechanism for SwiftData models. ### Properties - **name** (String) - The identifier or name of the store. ### Conforms To - **Copyable** - **DataStore** - **DataStoreBatching** - **Escapable** - **HistoryProviding** ### Usage DefaultStore is used to manage persistent storage in SwiftData applications, supporting batch requests and history tracking through its protocol conformances. ``` -------------------------------- ### GET SchemaMigrationPlan.stages Source: https://developer.apple.com/documentation/swiftdata/schemamigrationplan/stages Accesses the collection of migration stages defined for a schema migration plan. ```APIDOC ## GET SchemaMigrationPlan.stages ### Description Retrieves the array of MigrationStage objects that define the migration path between schema versions. ### Method static property ### Endpoint SchemaMigrationPlan.stages ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **stages** ([MigrationStage]) - An array of migration stages defining the transition process. #### Response Example [ { "stage": "MigrationStage.lightweight" }, { "stage": "MigrationStage.custom" } ] ``` -------------------------------- ### Query Initializers Source: https://developer.apple.com/documentation/swiftdata/query This section covers the different ways to create a Query instance, allowing for customization of data fetching through descriptors, predicates, sorting, and transaction options. ```APIDOC ## Query Initializers ### Creating a query `init(FetchDescriptor, animation: Animation)` Create a query with a SwiftData fetch descriptor. `init(filter: Predicate?, sort: [SortDescriptor], animation: Animation)` Create a query with a predicate, and a list of sort descriptors. `init(filter: Predicate?, sort: KeyPath, order: SortOrder, animation: Animation)` Creates a query with a predicate, a key path to a property for sorting, and the order to sort by. `init(filter: Predicate?, sort: KeyPath, order: SortOrder, animation: Animation)` Creates a query with a predicate, a key path to a property for sorting, and the order to sort by. `init(FetchDescriptor, transaction: Transaction?)` Create a query with a SwiftData fetch descriptor. `init(filter: Predicate?, sort: [SortDescriptor], transaction: Transaction?)` Create a query with a predicate, and a list of sort descriptors. `init(filter: Predicate?, sort: KeyPath, order: SortOrder, transaction: Transaction?)` Create a query with a predicate, a key path to a property for sorting, and the order to sort by. `init(filter: Predicate?, sort: KeyPath, order: SortOrder, transaction: Transaction?)` Create a query with a predicate, a key path to a property for sorting, and the order to sort by. ### Creating an unsorted, sectioned query `init(FetchDescriptor, animation: Animation, sectionBy: KeyPath?)` Creates a sectioned query from a fetch descriptor, grouped into sections by a String key path. `init(FetchDescriptor, animation: Animation, sectionBy: KeyPath?)` Creates a sectioned query from a fetch descriptor, grouped by an optional String key path. Beta `init(FetchDescriptor, transaction: Transaction?, sectionBy: KeyPath?)` Creates a sectioned query from a fetch descriptor, grouped by an optional String key path. Pass `nil` for the key path to disable sectioning. Beta `init(FetchDescriptor, transaction: Transaction?, sectionBy: KeyPath?)` Creates a sectioned query from a fetch descriptor, grouped into sections by a String key path. Pass `nil` to disable sectioning. Beta ``` -------------------------------- ### Query Initializer: init(filter:sort:order:animation:) Source: https://developer.apple.com/documentation/swiftdata/query/init%28filter%3Asort%3Aorder%3Aanimation%3A%29-1qfoj Creates a query with a predicate, a key path to a property for sorting, and the order to sort by, along with animation for UI updates. ```APIDOC ## init(filter:sort:order:animation:) ### Description Creates a query with a predicate, a key path to a property for sorting, and the order to sort by, along with animation for UI updates. ### Method `init` ### Endpoint N/A (Initializer) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift @MainActor @preconcurrency init(filter: Predicate? = nil, sort keyPath: KeyPath, order: SortOrder = .forward, animation: Animation) ``` ### Response #### Success Response (200) N/A (Initializer) #### Response Example N/A (Initializer) ### Usage Example ```swift struct RecipeList: View { // Recipes sorted by date of creation @Query(sort: \.dateCreated) var favoriteRecipes: [Recipe] var body: some View { List(favoriteRecipes) { RecipeDetails($0) } } } ``` ``` -------------------------------- ### GET Schema.Unique.constraints Source: https://developer.apple.com/documentation/swiftdata/schema/unique/constraints Accessing the constraints property to define unique identifiers for a SwiftData model. ```APIDOC ## GET Schema.Unique.constraints ### Description The `constraints` property is a final constant that returns an array of key paths, representing the unique constraints applied to a model schema. ### Method GET ### Endpoint Schema.Unique.constraints ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - N/A ### Request Example N/A ### Response #### Success Response (200) - **constraints** ([[PartialKeyPath]]) - An array of arrays of partial key paths representing the unique constraints. #### Response Example { "constraints": [["\KeyPath", "\KeyPath"]] } ``` -------------------------------- ### Fetching Models with FetchDescriptor Source: https://developer.apple.com/documentation/swiftdata/modelcontext Demonstrates how to fetch models using a FetchDescriptor. It includes methods for retrieving arrays, batched collections, and counting matching records. ```swift func fetch(FetchDescriptor) throws -> [T] func fetch(FetchDescriptor, batchSize: Int) throws -> FetchResultsCollection func fetchCount(FetchDescriptor) throws -> Int ``` -------------------------------- ### Access Store Identifier Source: https://developer.apple.com/documentation/swiftdata/persistentidentifier Gets the identifier of the store that contains the associated model, if available. ```swift var storeIdentifier: String? ``` -------------------------------- ### Creating a Schema Source: https://developer.apple.com/documentation/swiftdata/schemacomponents Initializers and protocols related to creating and versioning schemas. ```APIDOC ## See Also ### Creating a schema `init(Schema.Entity..., version: Schema.Version)` `init([any PersistentModel.Type], version: Schema.Version)` `convenience init(versionedSchema: any VersionedSchema.Type)` `protocol VersionedSchema` An interface for describing a specific version of a schema, including the models it contains. `init()` ``` -------------------------------- ### GET /HistoryDescriptor/predicate Source: https://developer.apple.com/documentation/swiftdata/historydescriptor/predicate Retrieves or configures the predicate used to filter transaction history records. ```APIDOC ## GET /HistoryDescriptor/predicate ### Description The predicate property defines the filtering criteria applied when initializing a history descriptor to retrieve specific transactions from the model store. ### Method GET ### Endpoint /HistoryDescriptor/predicate ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example N/A ### Response #### Success Response (200) - **predicate** (Predicate?) - The predicate used to filter the history data. #### Response Example { "predicate": "Predicate" } ``` -------------------------------- ### SwiftData Initializer with Migration Plan Source: https://developer.apple.com/documentation/swiftdata/datastore/init%28_%3Amigrationplan%3A%29 This Swift code snippet demonstrates the signature for the SwiftData `init(_:migrationPlan:)` initializer. It is used to create a new data store instance, optionally specifying a migration plan for handling schema changes. ```swift init( _ configuration: Self.Configuration, migrationPlan: (any SchemaMigrationPlan.Type)? ) throws ``` -------------------------------- ### GET /SchemaProperty/isUnique Source: https://developer.apple.com/documentation/swiftdata/schemaproperty/isunique Accessing the isUnique property of a SchemaProperty instance to determine if uniqueness constraints are applied. ```APIDOC ## GET /SchemaProperty/isUnique ### Description Retrieves the boolean value indicating whether the property is marked as unique within the data schema. ### Method GET ### Endpoint SchemaProperty.isUnique ### Parameters #### Path Parameters - None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **isUnique** (Bool) - Returns true if the property is unique, false otherwise. #### Response Example { "isUnique": true } ``` -------------------------------- ### Initializer: init(for:remappedIdentifiers:snapshotsToReregister:) Source: https://developer.apple.com/documentation/swiftdata/datastoresavechangesresult/init%28for%3Aremappedidentifiers%3Asnapshotstoreregister%3A%29 Initializes a DataStoreSaveChangesResult with a store identifier, remapped identifiers, and snapshots to re-register. ```APIDOC ## Initializer: init(for:remappedIdentifiers:snapshotsToReregister:) ### Description Initializes a `DataStoreSaveChangesResult` with a store identifier, remapped identifiers, and snapshots to re-register. This initializer is available on iOS 18.0+, iPadOS 18.0+, Mac Catalyst 18.0+, macOS 15.0+, tvOS 18.0+, visionOS 2.0+, watchOS 11.0+, and requires Swift 5.9+. ### Method `init` ### Endpoint N/A (Initializer) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift init( for storeIdentifier: String, remappedIdentifiers: [PersistentIdentifier : PersistentIdentifier] = [:], snapshotsToReregister: [PersistentIdentifier : T] = [:] ) ``` ### Response #### Success Response (200) N/A (Initializer) #### Response Example N/A (Initializer) ``` -------------------------------- ### GET /schemas Source: https://developer.apple.com/documentation/swiftdata/schemamigrationplan/schemas Access the collection of versioned schemas required for data model migration in SwiftData. ```APIDOC ## static var schemas ### Description A static property that returns an array of versioned schema types. This is used to define the migration path for your data models. ### Method Property Access ### Endpoint VersionedSchema.schemas ### Parameters #### Path Parameters - None ### Request Example N/A (Swift Property Access) ### Response #### Success Response (200) - **schemas** (Array) - An array containing the types that conform to VersionedSchema. #### Response Example [ SchemaV1.self, SchemaV2.self ] ``` -------------------------------- ### GET /schema/encodingVersion Source: https://developer.apple.com/documentation/swiftdata/schema/encodingversion Access the encodingVersion property to retrieve the schema version information for a SwiftData model. ```APIDOC ## GET /schema/encodingVersion ### Description Retrieves the current encoding version of the schema, which is used to manage data migration and compatibility across different versions of the application. ### Method GET ### Endpoint Schema.encodingVersion ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **encodingVersion** (Schema.Version) - The version identifier for the current schema. #### Response Example { "encodingVersion": "1.0.0" } ``` -------------------------------- ### init(_:animation:sectionBy:) Source: https://developer.apple.com/documentation/swiftdata/query/init%28_%3Aanimation%3Asectionby%3A%29-2pqhv Creates a sectioned query from a fetch descriptor, grouped by an optional String key path. This initializer is useful for displaying data in a sectioned list with animations. ```APIDOC ## init(_:animation:sectionBy:) ### Description Creates a sectioned query from a fetch descriptor, grouped by an optional String key path. ### Method `init` ### Parameters #### Path Parameters - `descriptor` (FetchDescriptor) - Required - The fetch descriptor for the query. - `animation` (Animation) - Required - The animation to apply to the query results. - `sectionKeyPath` (KeyPath?) - Optional - The key path to group elements by. If nil, sectioning is disabled. ### Response #### Success Response - `Result` ([Element]) - A sectioned array of elements. ``` -------------------------------- ### GET /PersistentIdentifier/storeIdentifier Source: https://developer.apple.com/documentation/swiftdata/persistentidentifier/storeidentifier Retrieves the unique identifier of the persistent store associated with a SwiftData model instance. ```APIDOC ## GET storeIdentifier ### Description Returns the identifier of the store that contains the associated model instance. This property is part of the PersistentIdentifier structure. ### Method GET ### Endpoint PersistentIdentifier.storeIdentifier ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **storeIdentifier** (String?) - The unique identifier of the persistent store, or nil if not associated. #### Response Example { "storeIdentifier": "com.apple.swiftdata.store.uuid" } ``` -------------------------------- ### Initialize Sectioned Query with FetchDescriptor, Animation, and KeyPath Source: https://developer.apple.com/documentation/swiftdata/query Creates a sectioned query from a FetchDescriptor, grouped by a String KeyPath, with animation support. This is a beta feature. ```swift init(FetchDescriptor, animation: Animation, sectionBy: KeyPath?) ``` -------------------------------- ### GET /modelcontext/fetch Source: https://developer.apple.com/documentation/swiftdata/modelcontext/fetch%28_%3A%29 Retrieves an array of persistent models that match the criteria defined in the provided FetchDescriptor. ```APIDOC ## GET /modelcontext/fetch ### Description Returns an array of typed models that match the criteria of the specified fetch descriptor. ### Method GET ### Endpoint ModelContext.fetch(descriptor: FetchDescriptor) ### Parameters #### Path Parameters - **descriptor** (FetchDescriptor) - Required - A fetch descriptor that provides the configuration for the fetch. ### Request Example ```swift let descriptor = FetchDescriptor(predicate: #Predicate { $0.name == "John" }) try context.fetch(descriptor) ``` ### Response #### Success Response (200) - **[T]** (Array) - An array of typed models that satisfy the criteria of the fetch descriptor. If no models match, the array is empty. #### Response Example ```json [ { "id": "1", "name": "John" }, { "id": "2", "name": "John" } ] ``` ``` -------------------------------- ### GET ModelContainer.mainContext Source: https://developer.apple.com/documentation/swiftdata/modelcontainer/maincontext Accesses the main model context associated with the application's main actor. ```APIDOC ## GET ModelContainer.mainContext ### Description Retrieves the ModelContext that is bound to the application's main actor. This context is typically used for UI-related data operations. ### Method GET ### Endpoint ModelContainer.mainContext ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **mainContext** (ModelContext) - The model context instance bound to the main actor. #### Response Example { "mainContext": "ModelContextInstance" } ``` -------------------------------- ### init(filter:sort:order:transaction:) Source: https://developer.apple.com/documentation/swiftdata/query/init%28filter%3Asort%3Aorder%3Atransaction%3A%29-2bx9a Initializes a Query property wrapper with a predicate, sorting key path, sort order, and transaction context. ```APIDOC ## init(filter:sort:order:transaction:) ### Description Creates a query with a predicate, a key path to a property for sorting, and the order to sort by. This is used within SwiftUI views to automatically fetch and update data. ### Method Initializer ### Parameters #### Parameters - **filter** (Predicate?) - Optional - A predicate on Element to filter the results. - **sort** (KeyPath) - Required - Key path to property used for sorting. - **order** (SortOrder) - Optional - Whether to sort in forward or reverse order (default: .forward). - **transaction** (Transaction?) - Optional - A transaction to use for user interface changes that result from changes to the fetched results. ### Request Example @Query(sort: \.dateCreated) var favoriteRecipes: [Recipe] ### Response #### Success Response - **Result** ([Element]) - An array of elements matching the filter and sort criteria. ``` -------------------------------- ### GET DataStoreSaveChangesRequest.editingState Source: https://developer.apple.com/documentation/swiftdata/datastoresavechangesrequest/editingstate Retrieves the current editing state of a save changes request object in SwiftData. ```APIDOC ## Property: editingState ### Description The `editingState` property provides access to the current state of modifications for a `DataStoreSaveChangesRequest`. It is used to determine the status of pending changes within the SwiftData persistence layer. ### Type `EditingState` ### Availability - iOS 18.0+ - macOS 15.0+ - Swift 5.9+ ### Declaration ```swift let editingState: EditingState ``` ### Usage Access this property to inspect whether the request is currently in a state that allows for saving or if it is locked due to ongoing operations. ``` -------------------------------- ### Initialize Query with Predicate, KeyPath Sort, and Transaction Source: https://developer.apple.com/documentation/swiftdata/query Creates a query with a Predicate, sorting by a specific property using a KeyPath, and a Transaction. Supports optional property values. ```swift init(filter: Predicate?, sort: KeyPath, order: SortOrder, transaction: Transaction?) ``` -------------------------------- ### initializeState(for:) Instance Method Source: https://developer.apple.com/documentation/swiftdata/datastore/initializestate%28for%3A%29-55cts Initializes the editing state for a SwiftData DataStore. ```APIDOC ## initializeState(for:) ### Description Initializes the editing state for a SwiftData DataStore. This method is available on iOS 18.0+, iPadOS 18.0+, Mac Catalyst 18.0+, macOS 15.0+, tvOS 18.0+, visionOS 2.0+, watchOS 11.0+ and requires Swift 5.9+. ### Method Instance Method ### Signature ```swift func initializeState(for editingState: EditingState) ``` ### Parameters #### Path Parameters - **editingState** (EditingState) - Required - The editing state to initialize. ``` -------------------------------- ### GET versionIdentifier Source: https://developer.apple.com/documentation/swiftdata/versionedschema/versionidentifier Retrieves the version identifier for a specific schema, used to track and manage data migrations. ```APIDOC ## GET versionIdentifier ### Description The versionIdentifier property provides a textual description or unique identifier for a migration's version or purpose within a SwiftData schema. ### Method GET ### Endpoint Schema.Version.versionIdentifier ### Parameters None ### Request Example N/A (Static property access) ### Response #### Success Response (200) - **versionIdentifier** (Schema.Version) - The static version identifier object associated with the schema. #### Response Example { "versionIdentifier": "1.0.0" } ``` -------------------------------- ### GET SchemaProperty.isRelationship Source: https://developer.apple.com/documentation/swiftdata/schemaproperty/isrelationship-ksdo Retrieves the boolean value indicating whether a property is defined as a relationship in the SwiftData schema. ```APIDOC ## GET SchemaProperty.isRelationship ### Description Returns a boolean value indicating whether the property is a relationship. This is part of the SwiftData SchemaProperty metadata. ### Method GET ### Endpoint SchemaProperty.isRelationship ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **isRelationship** (Bool) - Returns true if the property is a relationship, false otherwise. #### Response Example { "isRelationship": true } ``` -------------------------------- ### Create ModelContainer with Schema, Migration Plan, and Configurations (Swift) Source: https://developer.apple.com/documentation/swiftdata/modelcontainer/init%28for%3Amigrationplan%3Aconfigurations%3A%29-qof9 Initializes a `ModelContainer` using a provided schema, an optional migration plan, and a variable number of configurations. This initializer is crucial for setting up persistent storage with specific data models and migration strategies. It requires at least one configuration to be provided. ```swift convenience init( for givenSchema: Schema, migrationPlan: (any SchemaMigrationPlan.Type)? = nil, configurations: ModelConfiguration... ) throws ``` -------------------------------- ### GET /Schema/entitiesByName Source: https://developer.apple.com/documentation/swiftdata/schema/entitiesbyname Accesses the dictionary of entities defined within the SwiftData Schema, indexed by their string names. ```APIDOC ## GET /Schema/entitiesByName ### Description Retrieves a dictionary mapping entity names to their respective Schema.Entity definitions. This property is used to look up model blueprints by name. ### Method GET ### Endpoint Schema.entitiesByName ### Parameters None ### Request Example N/A (Property access) ### Response #### Success Response (200) - **entitiesByName** ([String : Schema.Entity]) - A dictionary where keys are entity names and values are the corresponding Schema.Entity objects. #### Response Example { "User": { "name": "User", "properties": [...] }, "Post": { "name": "Post", "properties": [...] } } ``` -------------------------------- ### Initializer: init(from:relatedBackingDatas:) Source: https://developer.apple.com/documentation/swiftdata/datastoresnapshot/init%28from%3Arelatedbackingdatas%3A%29 Initializes a new instance of a SwiftData type using a backing data source and related backing data. ```APIDOC ## Initializer: init(from:relatedBackingDatas:) ### Description Initializes a new instance of a SwiftData type using a backing data source and related backing data. ### Method Initializer ### Endpoint N/A (Initializer) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A (Initializer) #### Response Example N/A ### Availability iOS 18.0+ iPadOS 18.0+ Mac Catalyst 18.0+ macOS 15.0+ tvOS 18.0+ visionOS 2.0+ watchOS 11.0+ Swift 5.9+ ``` -------------------------------- ### init(_:transaction:sectionBy:) Source: https://developer.apple.com/documentation/swiftdata/query/init%28_%3Atransaction%3Asectionby%3A%29-5814o Creates a sectioned query from a fetch descriptor, grouped by an optional String key path. Pass `nil` for the key path to disable sectioning. ```APIDOC ## init(_:transaction:sectionBy:) ### Description Creates a sectioned query from a fetch descriptor, grouped by an optional String key path. Pass `nil` for the key path to disable sectioning. ### Signature ```swift init( _ descriptor: FetchDescriptor, transaction: Transaction? = nil, sectionBy sectionKeyPath: KeyPath? = nil ) where Result == [Element] ``` ### Parameters #### Path Parameters - **descriptor** (FetchDescriptor) - Required - The fetch descriptor for the query. - **transaction** (Transaction?) - Optional - The transaction to use for the query. - **sectionKeyPath** (KeyPath?) - Optional - The key path to group the query results by. Pass `nil` to disable sectioning. ``` -------------------------------- ### GET ModelContext.fetch(_:batchSize:) Source: https://developer.apple.com/documentation/swiftdata/modelcontext/fetch%28_%3Abatchsize%3A%29 Retrieves a collection of persistent models in batches based on a specified fetch descriptor. ```APIDOC ## GET fetch(_:batchSize:) ### Description Returns a collection of typed models, in batches, which match the criteria of the specified fetch descriptor. The context automatically fetches necessary batches as you access the collection. ### Method GET ### Endpoint ModelContext.fetch(descriptor: FetchDescriptor, batchSize: Int) ### Parameters #### Path Parameters - **descriptor** (FetchDescriptor) - Required - A fetch descriptor that provides the configuration for the fetch. - **batchSize** (Int) - Required - The maximum number of models to include in each batch. ### Request Example let descriptor = FetchDescriptor(predicate: #Predicate { $0.isActive }) let results = try modelContext.fetch(descriptor, batchSize: 50) ### Response #### Success Response (200) - **FetchResultsCollection** - A collection that efficiently provides the results of a completed fetch. #### Response Example // Returns a FetchResultsCollection containing the requested models. ``` -------------------------------- ### Initialize Query with Predicate, Sort Descriptors, and Transaction Source: https://developer.apple.com/documentation/swiftdata/query Creates a query with a Predicate for filtering and a list of SortDescriptors for ordering, along with a Transaction. ```swift init(filter: Predicate?, sort: [SortDescriptor], transaction: Transaction?) ``` -------------------------------- ### GET /ModelContext/fetchIdentifiers Source: https://developer.apple.com/documentation/swiftdata/modelcontext/fetchidentifiers%28_%3A%29 Retrieves an array of persistent identifiers for models that satisfy the criteria of a specified fetch descriptor. ```APIDOC ## fetchIdentifiers(_:) ### Description Returns an array of persistent identifiers, where each identifier represents a single model that satisfies the criteria of the specified fetch descriptor. ### Method Instance Method ### Endpoint ModelContext.fetchIdentifiers(_ descriptor: FetchDescriptor) ### Parameters #### Path Parameters - **descriptor** (FetchDescriptor) - Required - A fetch descriptor that provides the configuration for the fetch. ### Request Example let descriptor = FetchDescriptor(predicate: #Predicate { $0.isActive == true }) try context.fetchIdentifiers(descriptor) ### Response #### Success Response (200) - **[PersistentIdentifier]** (Array) - An array of persistent identifiers. If no models match, the array is empty. #### Response Example [PersistentIdentifier(id: "123"), PersistentIdentifier(id: "456")] ``` -------------------------------- ### GET ModelContext.hasChanges Source: https://developer.apple.com/documentation/swiftdata/modelcontext/haschanges Retrieves the Boolean status indicating if the current ModelContext has pending changes that require saving. ```APIDOC ## GET ModelContext.hasChanges ### Description A Boolean value that indicates whether the context has unsaved changes. This property is useful for determining if a save operation is necessary. ### Method GET ### Endpoint ModelContext.hasChanges ### Parameters None ### Request Example N/A (Instance Property) ### Response #### Success Response (200) - **hasChanges** (Bool) - Returns true if there are unsaved changes, false otherwise. #### Response Example { "hasChanges": true } ``` -------------------------------- ### Instance Properties and Methods Source: https://developer.apple.com/documentation/swiftdata/modelcontext Other instance properties and methods available on the model context. ```APIDOC ## Instance Properties and Methods ### Instance Properties - `var author: String?` - `var editingState: EditingState` ### Instance Methods - `func deleteHistory(HistoryDescriptor) throws` - `func fetchHistory(HistoryDescriptor) throws -> [T]` ``` -------------------------------- ### DefaultStore Class Overview Source: https://developer.apple.com/documentation/swiftdata/defaultstore Provides an overview of the DefaultStore class, its purpose, and its availability across different Apple platforms and Swift versions. ```APIDOC ## DefaultStore A data store that uses Core Data as its undelying storage mechanism. iOS 18.0+iPadOS 18.0+Mac Catalyst 18.0+macOS 15.0+tvOS 18.0+visionOS 2.0+watchOS 11.0+Swift 5.9+ ```swift final class DefaultStore ``` ``` -------------------------------- ### GET EditingState.author Source: https://developer.apple.com/documentation/swiftdata/editingstate/author Access the author property to retrieve or set the string identifier associated with the editing state. ```APIDOC ## GET EditingState.author ### Description Retrieves the author property from the EditingState instance. This property represents the entity responsible for the current state. ### Method GET ### Endpoint EditingState.author ### Parameters None ### Request Example N/A ### Response #### Success Response (200) - **author** (String?) - The author identifier or nil if not set. #### Response Example { "author": "John Doe" } ```