Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AnyModel #19

Open
leogdion opened this issue Nov 18, 2024 · 1 comment
Open

Add AnyModel #19

leogdion opened this issue Nov 18, 2024 · 1 comment

Comments

@leogdion
Copy link
Member

No description provided.

@leogdion
Copy link
Member Author

#if canImport(SwiftData)
  import BushelMachineData
  import Foundation
  public import SwiftData

  /// Phantom Type for easily retrieving fetching `PersistentModel` objects from a `ModelContext`.
  public struct AnyModel: Sendable, Identifiable {
    /// An error that is thrown when a `PersistentModel`
    /// with the specified `PersistentIdentifier` is not found.
    public struct NotFoundError: Error {
      /// The `PersistentIdentifier` of the `PersistentModel` that was not found.
      public let persistentIdentifier: PersistentIdentifier
    }

    /// The unique identifier of the model.
    public var id: PersistentIdentifier.ID { persistentIdentifier.id }

    /// The `PersistentIdentifier` of the model.
    public let persistentIdentifier: PersistentIdentifier

    /// Initializes a new `Model` instance with the specified `PersistentIdentifier`.
    ///
    /// - Parameter persistentIdentifier: The `PersistentIdentifier` of the model.
    public init(persistentIdentifier: PersistentIdentifier) {
      self.persistentIdentifier = persistentIdentifier
    }
  }

  extension AnyModel {
//    /// A boolean value indicating whether the model is temporary or not.
//    public var isTemporary: Bool {
//      self.persistentIdentifier.isTemporary ?? false
//    }

    /// Initializes a new `Model` instance with the specified `PersistentModel`.
    ///
    /// - Parameter model: The `PersistentModel` to initialize the `Model` with.
    public init(_ model: any PersistentModel) {
      self.init(persistentIdentifier: model.persistentModelID)
    }

    public init(typeErase: Model<some PersistentModel>) {
      self.init(persistentIdentifier: typeErase.persistentIdentifier)
    }
  }

  extension Model {
    public init(anyModel: AnyModel, type _: T.Type) {
      self.init(persistentIdentifier: anyModel.persistentIdentifier)
    }
  }
#endif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant