ftchirou / PredicateKit

🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.
MIT License
406 stars 19 forks source link

Add new sortDescriptor to FetchRequest extensions #8

Closed hfhbd closed 3 years ago

hfhbd commented 3 years ago

Hey, thanks for this nice library!

I am using iOS 15, which added a new property to the SwiftUI.FetchRequest, a sortDescriptor. It would be nice, if you could add this property in your extensions too, with @available(ios15)

Reference: https://developer.apple.com/documentation/swiftui/fetchrequest/init(sortdescriptors:predicate:animation:)-462jp?changes=latest_major

ftchirou commented 3 years ago

Hi @hfhbd 👋! PredicateKit's SwiftUI extension has support for sort descriptors. For example, it's possible to write something like the following.


import PredicateKit
import SwiftUI

struct ContentView: View {
  @SwiftUI.FetchRequest(
    fetchRequest: FetchRequest(predicate: (\Note.text).contains("Hello, World!"))
      .sorted(by: \Note.creationDate)
  )
  var notes: FetchedResults<Note>

  // ...
}

Does this match what you're requesting? 
hfhbd commented 3 years ago

Hey @ftchirou, yes I do know this function and I use it :) With iOS 15, Apple provided another constructor with sortDescriptor, so I would be nice to have to overload this SwiftUI.FetchRequest constructor with your FetchRequest too, to match the official constructor:

// For example, not tested
extension SwiftUI.FetchRequest {
  init(sortDescriptors: [SortDescriptor<Result>], predicate: Predicate? = nil, animation: Animation? = nil) {
    super.init(fetchRequest: FetchRequest(predicate: predicate).sorted(by: sortDescriptors)
  }
}

If you like it, I will provide a PR.

ftchirou commented 3 years ago

Hey @hfhbd! My apologies for the delay.

If you like it, I will provide a PR.

Yes, please open a PR when you have some time.

hfhbd commented 3 years ago

@ftchirou I developed the constructor, but the new SortDescriptor in Foundation is not compatible with your SortCriterion, because Apples implementation simple access the keyPath.name, whether SortCriterion requires a keyPath in the constructor. At the end, the new SortDescriptor in Foundation is finally a typed SortDescriptor, but unfortunately, your SortCriterion is more typed :D If you want to switch to the new SortDescriptor, this change would break your API, and it will require Swift 5.5.