# Structures

The following structures are available globally.

### From

- `From`

  A `From` clause specifies the source entity and source persistent store for fetch and query methods. A common usage is to just indicate the entity:

      let person = transaction.fetchOne(From<Person>())

  For cases where multiple `NSPersistentStore`s contain the same entity, the source configuration’s name needs to be specified as well:

      let person = transaction.fetchOne(From<Person>("Configuration1"))

  See more

  #### Declaration

  Swift

      public struct From<O> where O : DynamicObject

      extension From: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### GroupBy

- `GroupBy`

  The `GroupBy` clause specifies that the result of a query be grouped accoording to the specified key path.

  See more

  #### Declaration

  Swift

      public struct GroupBy<O> : GroupByClause, QueryClause, Hashable where O : DynamicObject

      extension GroupBy: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### Into

- `Into`

  An `Into` clause contains the destination entity and destination persistent store for a `create(...)` method. A common usage is to just indicate the entity:

      let person = transaction.create(Into<MyPersonEntity>())

  For cases where multiple `NSPersistentStore`s contain the same entity, the destination configuration’s name needs to be specified as well:

      let person = transaction.create(Into<MyPersonEntity>("Configuration1"))

  See more

  #### Declaration

  Swift

      public struct Into<O> : Hashable where O : DynamicObject

      extension Into: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### ListSnapshot

- `ListSnapshot`

  A `ListSnapshot` holds a stable list of `DynamicObject` identifiers. This is typically created by a `ListPublisher` and are designed to work well with `DiffableDataSource.TableViewAdapter`s and `DiffableDataSource.CollectionViewAdapter`s. For detailed examples, see the documentation on `DiffableDataSource.TableViewAdapter` and `DiffableDataSource.CollectionViewAdapter`.

  While the `ListSnapshot` stores only object identifiers, all accessors to its items return `ObjectPublisher`s, which are lazily created. For more details, see the documentation on `ListObject`.

  Since `ListSnapshot` is a value type, you can freely modify its items.

  See more

  #### Declaration

  Swift

      public struct ListSnapshot<O> : RandomAccessCollection, Hashable where O : DynamicObject

      extension ListSnapshot: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### LocalStorageOptions

- `LocalStorageOptions`

  The `LocalStorageOptions` provides settings that tells the `DataStack` how to setup the persistent store for `LocalStorage` implementers.

  See more

  #### Declaration

  Swift

      public struct LocalStorageOptions : OptionSet, ExpressibleByNilLiteral

      extension LocalStorageOptions: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### MigrationChain

- `MigrationChain`

  A `MigrationChain` indicates the sequence of model versions to be used as the order for progressive migrations. This is typically passed to the `SchemaHistory` or the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addStorage(...)` and its variants.

  Initializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to use the .xcdatamodel’s current version as the final version, and to disable progressive migrations:

      let dataStack = DataStack(migrationChain: nil)

  This means that the mapping model will be computed from the store’s version straight to the `DataStack`‘s model version. To support progressive migrations, specify the linear order of versions:

      let dataStack = DataStack(migrationChain:
         ["MyAppModel", "MyAppModelV2", "MyAppModelV3", "MyAppModelV4"])

  or for more complex migration paths, a version tree that maps the key-values to the source-destination versions:

      let dataStack = DataStack(migrationChain: [
          "MyAppModel": "MyAppModelV3",
          "MyAppModelV2": "MyAppModelV4",
          "MyAppModelV3": "MyAppModelV4"
      ])

  This allows for different migration paths depending on the starting version. The example above resolves to the following paths:

  - MyAppModel-MyAppModelV3-MyAppModelV4
  - MyAppModelV2-MyAppModelV4
  - MyAppModelV3-MyAppModelV4

  The `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met:

  - a version appears twice in an array
  - a version appears twice as a key in a dictionary literal
  - a loop is found in any of the paths
  See more

  #### Declaration

  Swift

      public struct MigrationChain : ExpressibleByNilLiteral, ExpressibleByStringLiteral, ExpressibleByDictionaryLiteral, ExpressibleByArrayLiteral, Equatable

      extension MigrationChain: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### ObjectSnapshot

- `ObjectSnapshot`

  The `ObjectSnapshot` is a full copy of a `DynamicObject`‘s properties at a given point in time. This is useful especially when keeping thread-safe state values, in ViewModels for example. Since this is a value type, any changes in this `struct` does not affect the actual object.

  See more

  #### Declaration

  Swift

      @dynamicMemberLookup
      public struct ObjectSnapshot<O> : ObjectRepresentation, Hashable where O : DynamicObject

      extension ObjectSnapshot: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### OrderBy

- `OrderBy`

  The `OrderBy` clause specifies the sort order for results for a fetch or a query.

  See more

  #### Declaration

  Swift

      public struct OrderBy<O> : OrderByClause, FetchClause, QueryClause, DeleteClause, Hashable where O : DynamicObject

      extension OrderBy: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### PartialObject

- `PartialObject`

  A `PartialObject` is only used when overriding getters and setters for `CoreStoreObject` properties. Custom getters and setters are implemented as a closure that “overrides” the default property getter/setter. The closure receives a `PartialObject<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties’ static typing, and so loading those info everytime KVO invokes this accessor method incurs a heavy performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `PartialObject<O>`, make sure to use `PartialObject<O>.persistentValue(for:)` instead of `PartialObject<O>.value(for:)`, which would unintentionally execute the same closure again recursively.

  See more

  #### Declaration

  Swift

      public struct PartialObject<O> where O : CoreStoreObject

      extension PartialObject: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### SectionBy

- `SectionBy`

  The `SectionBy` clause indicates the key path to use to group the `ListMonitor` objects into sections. An optional closure can also be provided to transform the value into an appropriate section index title:

      let monitor = dataStack.monitorSectionedList(
          From<Person>(),
          SectionBy("age") { "Age \($0)" },
          OrderBy(.ascending("lastName"))
      )

  See more

  #### Declaration

  Swift

      public struct SectionBy<O> where O : DynamicObject

      extension SectionBy: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### Select

- `Select`

  The `Select` clause indicates the attribute / aggregate value to be queried. The generic type is a `SelectResultType`, and will be used as the return type for the query.

  You can bind the return type by specializing the initializer:

      let maximumAge = dataStack.queryValue(
          From<MyPersonEntity>(),
          Select<Int>(.maximum("age"))
      )

  or by casting the type of the return value:

      let maximumAge: Int = dataStack.queryValue(
          From<MyPersonEntity>(),
          Select(.maximum("age"))
      )

  Valid return types depend on the query:

  - for `queryValue(...)` methods:
    - all types that conform to `QueryableAttributeType` protocol

  - for `queryAttributes(...)` methods:

    - `NSDictionary`
  See more

  #### Declaration

  Swift

      public struct Select<O, T> : SelectClause, Hashable where O : DynamicObject, T : SelectResultType

      extension Select: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

  #### Parameters

  `sortDescriptors` | a series of `NSSortDescriptor`s

### Tweak

- `Tweak`

  The `Tweak` clause allows fine-tuning the `NSFetchRequest` for a fetch or query. Sample usage:

      let employees = transaction.fetchAll(
          From<MyPersonEntity>(),
          Tweak { (fetchRequest) -> Void in
              fetchRequest.includesPendingChanges = false
              fetchRequest.fetchLimit = 5
          }
      )

  See more

  #### Declaration

  Swift

      public struct Tweak : FetchClause, QueryClause, DeleteClause

      extension Tweak: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### Where

- `Where`

  The `Where` clause specifies the conditions for a fetch or a query.

  See more

  #### Declaration

  Swift

      public struct Where<O> : WhereClauseType, FetchClause, QueryClause, DeleteClause, Hashable where O : DynamicObject

      extension Where: CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### VersionLock

- `VersionLock`

  The `VersionLock` contains the version hashes for entities. This is then passed to the `CoreStoreSchema`, which contains all entities for the store. An assertion will be raised if any `Entity` doesn’t match the version hash.

      class Animal: CoreStoreObject {
          let species = Value.Required<String>("species", initial: "")
          let nickname = Value.Optional<String>("nickname")
          let master = Relationship.ToOne<Person>("master")
      }
      class Person: CoreStoreObject {
          let name = Value.Required<String>("name", initial: "")
          let pet = Relationship.ToOne<Animal>("pet", inverse: { $0.master })
      }

      CoreStoreDefaults.dataStack = DataStack(
          CoreStoreSchema(
              modelVersion: "V1",
              entities: [
                  Entity<Animal>("Animal"),
                  Entity<Person>("Person")
              ],
              versionLock: [
                  "Animal": [0x2698c812ebbc3b97, 0x751e3fa3f04cf9, 0x51fd460d3babc82, 0x92b4ba735b5a3053],
                  "Person": [0xae4060a59f990ef0, 0x8ac83a6e1411c130, 0xa29fea58e2e38ab6, 0x2071bb7e33d77887]
              ]
          )
      )

  See more

  #### Declaration

  Swift

      public struct VersionLock : ExpressibleByDictionaryLiteral, Equatable

      extension VersionLock: CustomStringConvertible, CustomDebugStringConvertible, CoreStoreDebugStringConvertible

### FetchChainBuilder

- `FetchChainBuilder`

  The fetch builder type used for fetches. A `FetchChainBuilder` is created from a `From` clause.

      let people = source.fetchAll(
          From<MyPersonEntity>()
              .where(\.age > 18)
              .orderBy(.ascending(\.age))
      )

  See more

  #### Declaration

  Swift

      public struct FetchChainBuilder<O> : FetchChainableBuilderType where O : DynamicObject

### QueryChainBuilder

- `QueryChainBuilder`

  The fetch builder type used for a queries. A `QueryChainBuilder` is created from a `From` clause and then a `select(...)` chain.

      let averageAdultAge = dataStack.queryValue(
          From<MyPersonEntity>()
              .select(Int.self, .average(\.age))
              .where(\.age > 18)
      )

  See more

  #### Declaration

  Swift

      public struct QueryChainBuilder<O, R> : QueryChainableBuilderType where O : DynamicObject, R : SelectResultType

### SectionMonitorChainBuilder

- `SectionMonitorChainBuilder`

  The fetch builder type used for a sectioned `ListMonitor`. A `SectionMonitorChainBuilder` is created from a `From` clause and then a `sectionBy(...)` chain.

      let monitor = transaction.monitorSectionedList(
          From<MyPersonEntity>()
              .sectionBy(\.age, { "\($0!) years old" })
              .where(\.age > 18)
              .orderBy(.ascending(\.age))
      )

  See more

  #### Declaration

  Swift

      public struct SectionMonitorChainBuilder<O> : SectionMonitorBuilderType where O : DynamicObject

### ListReader

- `ListReader`

  A container view that reads list changes in a `ListPublisher`

  See more

  #### Declaration

  Swift

      public struct ListReader<Object, Content, Value> : View where Object : DynamicObject, Content : View

### ListState

- `ListState`

  A property wrapper type that can read `ListPublisher` changes.

  See more

  #### Declaration

  Swift

      @propertyWrapper
      public struct ListState<Object> : DynamicProperty where Object : DynamicObject

### ObjectProxy

- `ObjectProxy`

  An `ObjectProxy` is only used when overriding getters and setters for `CoreStoreObject` properties. Custom getters and setters are implemented as a closure that “overrides” the default property getter/setter. The closure receives an `ObjectProxy<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties’ static typing, and so loading those info every time KVO invokes this accessor method incurs a heavy performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `ObjectProxy<O>`, make sure to use `ObjectProxy<O>.$property.primitiveValue` instead of `ObjectProxy<O>.$property.value`, which would execute the same accessor again recursively.

  See more

  #### Declaration

  Swift

      @dynamicMemberLookup
      public struct ObjectProxy<O> where O : CoreStoreObject

### ObjectReader

- `ObjectReader`

  A container view that reads changes to an `ObjectPublisher`

  See more

  #### Declaration

  Swift

      public struct ObjectReader<Object, Content, Placeholder, Value> : View where Object : DynamicObject, Content : View, Placeholder : View

### ObjectState

- `ObjectState`

  A property wrapper type that can read `ObjectPublisher` changes.

  See more

  #### Declaration

  Swift

      @propertyWrapper
      public struct ObjectState<O> : DynamicProperty where O : DynamicObject