I’m using Swift Charts in my app to display data in a visual way. For that (as well as some sum calculations) I’d like to create a fetch request that searches for all the data in a given time range plus one older and newer entry.
Building a predicate that searches for a time range is easy, but how can I tell the fetch request that I would also like to have the first entry that comes before that time range and the first that comes after? I don’t know when these entries appear, so I can’t extend the time range.
Example
Let’s say I have the following data (timestamp – value):
- Feb 1, 2024 – 20
- Oct 1, 2024 – 30
- Jan 1, 2025 – 40
- Sep 1, 2025 – 50
- May 1, 2026 – 60
- Oct 1, 2026 – 70
Now I want to search for the range Jan to Dec 2025. How can I retrieve the two entries that are in the range (No. 3 & 4) as well as the first entry before (No. 2) and the first after that (No. 5)? Without knowing the timestamp of No. 2 and 5.
I’d appreciate some best practices or tips how to handle this special case. 🙏
Hi Alexander216,
the FetchRequest/Predicate can't express what you are looking for.
To fetch the data you are looking for, you'd have to
- Use a fetch request with a predicate for values between Oct 1st 2024 and May 1st 2026 to fetch all the values in the range. Results 2–5 in your example.
- Create a fetch request with a date less than the first result, with a backward sort order and a limit of 1.
- Create a fetch request with a date greater than the last result, with a forward sort order and a limit of 1.