├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── Package.swift ├── README.md └── Sources └── SectionedQuery ├── Array+Ext.swift ├── SectionedQuery.swift └── SectionedResults.swift /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/ 7 | .netrc 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/). 7 | 8 | ## [1.2.0] - 2024-06-12 9 | 10 | * **Add `filter` function** ([#2](#2)) 11 | 12 | `SectionedResults` now has a `filter` function that returns a new `SectionedResults` object containing, in order, the elements that satisfy the given predicate. 13 | 14 | ## [1.1.0] - 2024-05-09 15 | 16 | * **Conform to `Equatable`** ([#1](#1)) 17 | 18 | `SectionedResults` now conforms to `Equatable`. 19 | 20 | ## [1.0.0] - 2023-09-27 21 | 22 | Initial release. 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Thomas Magis-Agosta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "swiftdata-sectionedquery", 7 | platforms: [ 8 | .iOS(.v17), 9 | .macOS(.v14), 10 | .tvOS(.v17), 11 | .watchOS(.v10), 12 | .visionOS(.v1) 13 | ], 14 | products: [ 15 | .library( 16 | name: "SectionedQuery", 17 | targets: ["SectionedQuery"]), 18 | ], 19 | targets: [ 20 | .target( 21 | name: "SectionedQuery") 22 | ] 23 | ) 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SectionedQuery 2 | 3 | A property wrapper that fetches a set of SwiftData models, grouped into 4 | sections, and keeps those models in sync with the underlying data. 5 | 6 | ## Table of Contents 7 | 8 | - [Intent](#intent) 9 | - [Features](#features) 10 | - [Supported Platforms](#supported-platforms) 11 | - [Example Usage](#example-usage) 12 | - [Usage Notes](#usage-notes) 13 | - [License](#license) 14 | 15 | ## Intent 16 | 17 | Originally announced at WWDC 2023, SwiftData makes it easy to persist 18 | data using declarative code. The framework includes a new `@Query` property 19 | wrapper that fetches a set of models, similar to the `@FetchRequest` 20 | property wrapper used with a CoreData stack. 21 | 22 | However, SwiftData does not currently include a property wrapper that 23 | fetches models grouped into sections, similar to the `@SectionedFetchRequest` 24 | property wrapper used with a CoreData stack. 25 | 26 | This package fills this gap in the SwiftData framework by providing a 27 | `@SectionedQuery` property wrapper and `SectionedResults` type that makes 28 | it easy to write sectioned queries and use the data in your views. 29 | 30 | ## Features 31 | 32 | - **Multiple Initializers** 33 | 34 | Initializers for `@SectionedQuery` that match those for `@Query`, 35 | making it easy to build your queries using any mix of predicates, sort 36 | descriptors, animations, and more. 37 | 38 | - **Automatic View Updates** 39 | 40 | `@SectionedQuery` will automatically trigger an update of the view when the 41 | underlying data changes, so there's no need to trigger a manual refresh. 42 | 43 | - **Iterable Result Type** 44 | 45 | The `SectionedResults` type conforms to `RandomAccessCollection`, making it 46 | easy to iterate over each section and its elements without any complex code. 47 | 48 | ## Supported Platforms 49 | 50 | The following platforms are supported: 51 | 52 | - iOS 17.0+ 53 | - macOS 14.0+ 54 | - tvOS 13.0+ 55 | - watchOS 10.0+ 56 | - visionOS 1.0+ 57 | 58 | ## Example Usage 59 | 60 | Use `@SectionedQuery` in your SwiftUI views to fetch data, just like you would 61 | with `@Query`. Simply specify the property of your model to section results by 62 | and set the type to `SectionedResults`. 63 | 64 | ```swift 65 | import SwiftData 66 | import SectionedQuery 67 | 68 | 69 | @Model 70 | class Item { 71 | 72 | @Attribute(.unique) var name: String 73 | var kind: String 74 | 75 | } 76 | 77 | 78 | struct ContentView: View { 79 | 80 | @SectionedQuery(\.kind) private var results: SectionedResults 81 | 82 | var body: some View { 83 | List(results) { section in 84 | Section(section.id) { 85 | ForEach(section) { item in 86 | Text(item.name) 87 | } 88 | } 89 | } 90 | } 91 | 92 | } 93 | ``` 94 | 95 | If you want to support dynamic sectioned queries, you can set the property from 96 | the view's initializer, passing in any relevant parameters. 97 | 98 | ```swift 99 | import SwiftData 100 | import SectionedQuery 101 | 102 | 103 | @Model 104 | class Item { 105 | 106 | @Attribute(.unique) var name: String 107 | var kind: String 108 | 109 | } 110 | 111 | 112 | struct DynamicContentView: View { 113 | 114 | @SectionedQuery private var results: SectionedResults 115 | 116 | var body: some View { 117 | List(results) { section in 118 | Section(section.id) { 119 | ForEach(section) { item in 120 | Text(item.name) 121 | } 122 | } 123 | } 124 | } 125 | 126 | init(order: SortOrder) { 127 | _results = SectionedQuery(\.kind, order: order) 128 | } 129 | 130 | } 131 | ``` 132 | 133 | ## Usage Notes 134 | 135 | When using the `@SectionedQuery` property wrapper, there are a few important 136 | things to keep in mind: 137 | 138 | - The model property that you section results by must conform to `Hashable`. 139 | 140 | - The `SectionedResults` type must be specialized: 141 | 142 | - `SectionIdentifier` must match the type of the model property you section 143 | results by. It must conform to `Hashable`. 144 | 145 | - `Result` must match the type of the model you are querying. It must 146 | conform to `PersistentModel`. 147 | 148 | Because `SectionedResults` conforms to `RandomAccessCollection`, you can easily 149 | use it with SwiftUI views like `List` and `ForEach`. 150 | 151 | ## License 152 | 153 | This package is distributed under [The MIT License](./LICENSE). 154 | -------------------------------------------------------------------------------- /Sources/SectionedQuery/Array+Ext.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // 4 | // 5 | // Created by Thomas Magis-Agosta on 9/27/23. 6 | // 7 | 8 | import Foundation 9 | 10 | internal extension Array where Iterator.Element: Hashable { 11 | 12 | func uniqued() -> [Element] { 13 | var seen: Set = [] 14 | return filter { seen.insert($0).inserted } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Sources/SectionedQuery/SectionedQuery.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SectionedQuery.swift 3 | // 4 | // Created by Thomas Magis-Agosta on 9/27/23. 5 | // 6 | 7 | import SwiftData 8 | import SwiftUI 9 | 10 | /// A property wrapper that fetches a set of models, grouped into sections, and keeps those models 11 | /// in sync with the underlying data. 12 | /// 13 | @available(iOS 17, macOS 14, tvOS 17, watchOS 10, visionOS 1, *) 14 | @propertyWrapper 15 | public struct SectionedQuery: DynamicProperty 16 | where SectionIdentifier: Hashable, Element: PersistentModel { 17 | 18 | /// A type that represents the results of the sectioned query. 19 | public typealias Results = SectionedResults 20 | 21 | @Query private var elements: [Element] 22 | 23 | private let sectionIdentifier: KeyPath 24 | 25 | 26 | /// An error encountered during the most recent attempt to fetch data. 27 | /// 28 | public var fetchError: (Error)? { 29 | _elements.fetchError 30 | } 31 | 32 | 33 | /// Current model context SectionedQuery interacts with. 34 | /// 35 | public var modelContext: ModelContext { 36 | _elements.modelContext 37 | } 38 | 39 | 40 | /// The most recent fetched result from the SectionedQuery. 41 | /// 42 | public var wrappedValue: Results { 43 | get { 44 | SectionedResults(sectionIdentifier: sectionIdentifier, 45 | results: elements) 46 | } 47 | } 48 | 49 | 50 | /// Updates the underlying value of the stored value. 51 | /// 52 | public func update() { 53 | _elements.update() 54 | } 55 | 56 | 57 | /// Create a sectioned query. 58 | /// 59 | public init(_ sectionIdentifier: KeyPath) { 60 | self.sectionIdentifier = sectionIdentifier 61 | _elements = Query() 62 | } 63 | 64 | 65 | /// Create a sectioned query with a SwiftData predicate. 66 | /// 67 | public init(_ sectionIdentifier: KeyPath, 68 | filter: Predicate) { 69 | self.sectionIdentifier = sectionIdentifier 70 | _elements = Query(filter: filter) 71 | } 72 | 73 | 74 | /// Create a sectioned query with a predicate and a list of sort descriptors. 75 | /// 76 | public init(_ sectionIdentifier: KeyPath, 77 | filter: Predicate? = nil, 78 | sort descriptors: [SortDescriptor] = [], 79 | transaction: Transaction? = nil) { 80 | self.sectionIdentifier = sectionIdentifier 81 | _elements = Query(filter: filter, 82 | sort: descriptors, 83 | transaction: transaction) 84 | } 85 | 86 | 87 | /// Create a sectioned query with a predicate, a key path to a property for sorting, 88 | /// and the order to sort by. 89 | /// 90 | public init(_ sectionIdentifier: KeyPath, 91 | filter: Predicate? = nil, 92 | sort keyPath: KeyPath, 93 | order: SortOrder = .forward, 94 | transaction: Transaction? = nil) where Value: Comparable { 95 | self.sectionIdentifier = sectionIdentifier 96 | _elements = Query(filter: filter, 97 | sort: keyPath, 98 | order: order, 99 | transaction: transaction) 100 | } 101 | 102 | 103 | /// Create a sectioned query with a predicate and a list of sort descriptors. 104 | /// 105 | public init(_ sectionIdentifier: KeyPath, 106 | filter: Predicate? = nil, 107 | sort descriptors: [SortDescriptor] = [], 108 | animation: Animation) { 109 | self.sectionIdentifier = sectionIdentifier 110 | _elements = Query(filter: filter, 111 | sort: descriptors, 112 | animation: animation) 113 | } 114 | 115 | 116 | /// Create a sectioned query with a predicate, a key path to a property for sorting, 117 | /// and the order to sort by. 118 | /// 119 | public init(_ sectionIdentifier: KeyPath, 120 | filter: Predicate? = nil, 121 | sort keyPath: KeyPath, 122 | order: SortOrder = .forward, 123 | animation: Animation = .easeInOut) where Value: Comparable { 124 | self.sectionIdentifier = sectionIdentifier 125 | _elements = Query(filter: filter, 126 | sort: keyPath, 127 | order: order, 128 | animation: animation) 129 | } 130 | 131 | 132 | /// Create a sectioned query with a predicate, a key path to a property for sorting, 133 | /// and the order to sort by. 134 | /// 135 | public init(_ sectionIdentifier: KeyPath, 136 | filter: Predicate? = nil, 137 | sort keyPath: KeyPath, 138 | order: SortOrder = .forward, 139 | transaction: Transaction? = nil) where Value: Comparable { 140 | self.sectionIdentifier = sectionIdentifier 141 | _elements = Query(filter: filter, 142 | sort: keyPath, 143 | order: order, 144 | transaction: transaction) 145 | } 146 | 147 | 148 | /// Create a sectioned query with a SwiftData fetch descriptor. 149 | /// 150 | public init(_ sectionIdentifier: KeyPath, 151 | fetchDescriptor: FetchDescriptor, 152 | transaction: Transaction? = nil) { 153 | self.sectionIdentifier = sectionIdentifier 154 | _elements = Query(fetchDescriptor, 155 | transaction: transaction) 156 | } 157 | 158 | 159 | /// Create a sectioned query with a SwiftData fetch descriptor. 160 | /// 161 | public init(_ sectionIdentifier: KeyPath, 162 | fetchDescriptor: FetchDescriptor, 163 | animation: Animation) { 164 | self.sectionIdentifier = sectionIdentifier 165 | _elements = Query(fetchDescriptor, 166 | animation: animation) 167 | } 168 | 169 | } 170 | -------------------------------------------------------------------------------- /Sources/SectionedQuery/SectionedResults.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SectionedResults.swift 3 | // 4 | // Created by Thomas Magis-Agosta on 9/27/23. 5 | // 6 | 7 | import SwiftData 8 | import SwiftUI 9 | 10 | /// A collection of models retrieved from a SwiftData persistent store, grouped into sections. 11 | /// 12 | @available(iOS 17, macOS 14, tvOS 17, watchOS 10, visionOS 1, *) 13 | public struct SectionedResults: Equatable, RandomAccessCollection 14 | where SectionIdentifier: Hashable, Result: PersistentModel { 15 | 16 | /// A type that represents an element in the collection. 17 | public typealias Element = SectionedResults.Section 18 | /// A type that represents a position in the collection. 19 | public typealias Index = Int 20 | /// A type that represents the indices that are valid for subscripting the collection, in ascending order. 21 | public typealias Indices = Range 22 | /// A type that provides the collection’s iteration interface and encapsulates its iteration state. 23 | public typealias Iterator = IndexingIterator> 24 | /// A collection representing a contiguous subrange of this collection’s elements. The subsequence shares indices with the original collection. 25 | public typealias SubSequence = Slice> 26 | 27 | /// The key path that the system uses to group results into sections. 28 | public var sectionIdentifier: KeyPath 29 | /// The collection of results that share a specified identifier. 30 | public var sections: [Section] 31 | /// The index of the first section in the results collection. 32 | public var startIndex: Int = 0 33 | /// The index that’s one greater than that of the last section. 34 | public var endIndex: Int { sections.count } 35 | 36 | 37 | /// Gets the section at the specified index. 38 | public subscript(position: Int) -> Section { 39 | get { sections[position] } 40 | } 41 | 42 | /// Conform to equatable 43 | public static func == (lhs: SectionedResults, rhs: SectionedResults) -> Bool { 44 | if lhs.sections.count != rhs.sections.count { return false } 45 | else if lhs.sections.count < 1 && rhs.sections.count < 1 { return true } 46 | else { 47 | for range in 0...lhs.sections.count-1 { 48 | 49 | if lhs.sections[range].elements.count != rhs.sections[range].elements.count { 50 | return false 51 | } 52 | } 53 | return true 54 | } 55 | } 56 | 57 | 58 | internal init(sectionIdentifier: KeyPath, results: [Result]) { 59 | self.sectionIdentifier = sectionIdentifier 60 | 61 | let groupedResults = Dictionary(grouping: results) { result in 62 | result[keyPath: sectionIdentifier] 63 | } 64 | 65 | let identifiers = results.map { result in 66 | result[keyPath: sectionIdentifier] 67 | }.uniqued() 68 | 69 | self.sections = identifiers.compactMap { identifier in 70 | guard let elements = groupedResults[identifier] else { return nil } 71 | return Section(id: identifier, elements: elements) 72 | } 73 | } 74 | 75 | 76 | public func filter(_ isIncluded: (Result) throws -> Bool) rethrows -> Self { 77 | let elements = sections.flatMap { $0.elements } 78 | let filteredElements = try elements.filter(isIncluded) 79 | return .init(sectionIdentifier: sectionIdentifier, results: filteredElements) 80 | } 81 | 82 | 83 | /// The collection of models that share a specified identifier. 84 | /// 85 | public struct Section: RandomAccessCollection, Identifiable { 86 | 87 | /// A type that represents an element in the collection. 88 | public typealias Element = Result 89 | /// A type that represents the ID of the collection. 90 | public typealias ID = SectionIdentifier 91 | /// A type that represents a position in the collection. 92 | public typealias Index = Int 93 | /// A type that represents the indices that are valid for subscripting the collection, in ascending order. 94 | public typealias Indices = Range 95 | /// A type that provides the collection’s iteration interface and encapsulates its iteration state. 96 | public typealias Iterator = IndexingIterator.Section> 97 | /// A collection representing a contiguous subrange of this collection’s elements. The subsequence shares indices with the original collection. 98 | public typealias SubSequence = Slice.Section> 99 | 100 | /// The section identifier. 101 | public var id: ID 102 | /// The collection of results for the section. 103 | public var elements: [Element] 104 | /// The index of the first element in the results collection. 105 | public var startIndex: Int = 0 106 | /// The index that’s one greater than that of the last element. 107 | public var endIndex: Int { elements.count } 108 | 109 | 110 | /// Gets the element at the specified index. 111 | public subscript(position: Int) -> Result { 112 | get { elements[position] } 113 | } 114 | 115 | 116 | internal init(id: ID, elements: [Element]) { 117 | self.id = id 118 | self.elements = elements 119 | } 120 | 121 | } 122 | 123 | } 124 | --------------------------------------------------------------------------------