Beginners’ Advice for Swift / SwiftUI with CoreData (1)

Ess Martin
3 min readJul 25, 2020

--

Code-Generation and Class-Extensions

Introduction:

For several weeks now, I have been learning Swift 5 with SwiftUI and came across many tutorials and examples that show only the fastest but not necessarily the most sustainable way. With this article I want to show the differences between the fast and sustainable approaches. I want to point out, that I’m still a beginner and that there are certainly much better ways to reach your goal. Nevertheless, I would like to describe my approach, since I as a beginner understand this approach well and therefore think that other beginners may also profit from this sustainable method.

XCode/CoreData “Code generation”:

There is a variety of examples for Core Data with Swift/SwiftUI that show how to set up the entities and attributes. In most cases it is recommended to set the code generation to “Manual/None”.

SCREENSHOT XCode Settings Projectname.xcdatamodeld by Ess Martin

This recommendation is probably based on the assumption that the configuration of the entities and attributes is done once and is not continuously extended and changed. However, this is hardly the case in real projects. In real projects, the configuration will often be changed and optimized. As a result, the classes have to be generated manually very often.

My suggestion is to set this setting to “Class Definition”. In this case the attributes are managed automatically and are therefore, always up to date. This procedure saves you a lot of unnecessary work. In addition, this prevents the accidental deletion of extensions that have been made in the existing class (extensions).

XCode/CoreData “Class extensions”:

When it comes to class extensions, the approach in most examples is not focused on sustainability. In most cases, the generated class extension is expanded manually. With the setting “Manual/None”, the extensions have to be migrated manually each time, creating unnecessary steps and a possible source of error.

SCREENSHOT — XCode generated extension without own changes by Martin Ess

My suggestion is to always create a separate file with the additional extensions, regardless of the code generation settings. This file will then remain unaffected by the regenerations. This approach makes it possible to replace the two existing generated files with the newly generated ones promptly.

SCREENSHOT — Self-written extensions (sample) by Martin Ess

If you have any suggestions or ideas, I would be happy to hear from you and exchange opinions.

--

--

Ess Martin

I’ve been in IT for almost 30 years. Love to travel. Love learning new skills. I speak german natively, so sorry if my english is not the best :)