SwiftUI: Using CoreData

Don’t forget this!

Image for post
Image for post
Photo by Amanda Frank

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12, and Swift 5.3

Create project

In order to develop a new SwiftUI project that uses Core Data you will need to open Xcode, perhaps press but certainly remember to press the rather friendly Core Data tick box.

Image for post
Image for post

The approach

I have been a cheerleader for a modular Core Data Approach — this means that it should be trestable. Apple have created their Core Data template, and this seems to suggest that the Core Data reaches right into the views in SwiftUI.

To that? I say there must be a testable way. However, I’m still going to use the file (so this article may age badly as the template changes.

The Tests

These tests are in no way complete. In fact, testing saving and the number of objects we have after that operation isn’t ideal. However, this is a basis of how we might test a DataManager module and we can test that in a modular fashion.

Remember: I’m not saying that the in terms of testing is perfect, but it a nudge in the right direction.

Actually that is true of the main data manager; I’m not comfortable with my naming of either, but this is a pointer in the right direction rather than complete production-ready code.

Oh yes, don’t leave print logs in your code like that if it is for production use (and perhaps deal with errors in a professional way to).

Linking to SwiftUI:

This is where the work is done. This means that we are going to inject the data manager (so mocking is possible, although here I can use the preview data in the persistence controller):

The ContentView

The content view will be reasonably familiar for those who have previously used [SwiftUI](), with the data presented in a List, as you can see in the code below:

Then you can choose to to run the tests and, well they are all ✅. The mark of a successful project? Well, in this case the tests are there for you to improve and to work on and get sufficient coverage to make this a production project, so in my opinion this comes under a “good start”.

Conclusion

Want to look at the whole thing? This Repo has the whole network manager, which some will find easier to follow along with.

This project isn’t (yet) production-ready, but it is a good start and is something for you to work on and think about how to make your projects better. SwiftUI isn’t scary, and I hope this demonstration has gone some way to give you some direction in your own coding.

Thanks for reading!

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store