Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Last active September 10, 2024 17:24
Show Gist options
  • Save ryanlintott/43407296f6adf3a1529282c6d7a16c58 to your computer and use it in GitHub Desktop.
Save ryanlintott/43407296f6adf3a1529282c6d7a16c58 to your computer and use it in GitHub Desktop.
A fetch method that uses a parameter pack to fetch one or more PersistentModel types then runs a closure to return a Sendable result.
import SwiftData
extension ModelContext {
/// FetchDescriptor is Sendable but inside a parameter pack there are sometimes issues with this working in Swift 6.0
func fetch<each T: PersistentModel, Result: Sendable>(
_ descriptor: repeat FetchDescriptor<each T>,
with closure: @escaping @Sendable (repeat [each T]) throws -> Result
) throws -> Result {
try closure(repeat try fetch(each descriptor))
}
/// An option with a pack of closures that return FetchDescriptors
func fetch<each T: PersistentModel, Result: Sendable>(
_ descriptor: repeat @escaping @Sendable() -> FetchDescriptor<each T>,
with closure: @escaping @Sendable (repeat [each T]) throws -> Result
) throws -> Result {
try closure(repeat try fetch((each descriptor)()))
}
/// An option with a single closure that returns a Tuple parameter pack of FetchDescriptor
func fetch<each T: PersistentModel, Result: Sendable>(
_ descriptor: @escaping @Sendable () -> (repeat FetchDescriptor<each T>),
with closure: @escaping @Sendable (repeat [each T]) throws -> Result
) throws -> Result {
return try closure(repeat try fetch(each descriptor()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment