HomeiOS DevelopmentPredicates with generics

Predicates with generics


I’m attempting to make use of Predicate with generics however I preserve getting the next compilation error :

Can not convert worth of kind 'PredicateExpressions.Equal<PredicateExpressions.ConditionalCast<PredicateExpressions.KeyPath<PredicateExpressions.Variable<E.EntityType>, E.EntityType.PrimaryKey?>, Key>, PredicateExpressions.Worth<Non-obligatory<Key>>>' to closure consequence kind 'any StandardPredicateExpression<Bool>'

I’ve the next :

public protocol Entity {
  associatedtype DomainModel
  associatedtype PrimaryKey: Equatable

  /// The entity's area mannequin
  var domainModel: DomainModel { get }
  /// The entity's main key
  var primaryKey: PrimaryKey { get }
}

public protocol DomainEntity {
  associatedtype EntityType: PersistentModel & Entity

  var entity: EntityType? { get }
}

@ModelActor
actor DataSource<E: DomainEntity> {
  typealias Mannequin = E.EntityType.DomainModel

  func get<Key: Equatable>(by key: Key) throws -> Mannequin? {
    let predicate: Predicate<E.EntityType> = #Predicate {
      ($0.primaryKey as? Key) == key // I’m having the error right here
    }
    let fetchDescriptor = FetchDescriptor<E.EntityType>(predicate: predicate)

    guard let entity: E.EntityType = attempt modelContext.fetch(fetchDescriptor).first else {
      return nil
    }

    guard let mannequin = entity.domainModel as? Mannequin else {
      throw DatabaseError.conversionFailed
    }
    return mannequin
  }
}

I get that the error is type of explaining that it may possibly’t work out the underlying varieties, however as each properties are Equatable, it shouldn’t be a difficulty.

Does anybody have an concept of how I may do such a comparability utilizing predicates? Or is there one other means?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments