Post

Replies

Boosts

Views

Activity

How to count rows in SwiftData?
I'm currently writing an app that loads URLs from the HackerNews API. I have implemented Bookmarks by persisting any bookmarked data to SwiftData. I am currently trying to implemented "viewed links" — i.e. if you click a link, it gets marked as viewed — I was able to do so by persisting the link ID to SwiftData and in each link view, it queries for itself against the existing "viewed" links, like so: static func viewedPredicate(_ id: Int) -> Predicate<Viewed> { return #Predicate<Viewed> { $0.id == id } } var viewed: [Viewed] { return (try? modelContext.fetch( FetchDescriptor( predicate: ItemView.viewedPredicate(id) ))) ?? [] } But now, I want to provide stats to the user, so I need to count how many viewed links exist. I don't want to return ALL objects from SwiftData, I want a simple Int that tells me how many there are. To do so, I implemented it as follows: private var viewedCount: Int { return (try? modelContext.fetchCount(FetchDescriptor<Viewed>())) ?? 0 } But when I delete the stats, the number does not get updated. I get that the current approach is "unaware" of the link between the data and the view, but that's precisely my question. How can I make the query update when the underlying model gets updated too? I've searched far and wide and the best result I found was to simply use the @Query over Viewed and count after, this could be done purely on the SQLite side so I'm looking for a better solution.
1
1
952
Oct ’23