Overcoming Adversity using Swift 1.2 and Mogenerator

July 20, 2015 | Stefan Mischook

Hi,

My brother (Richard Mischook) has been building iOS apps for a little while, and he recently decided to start working with Swift. So he offered this short little article, that might help people who are migrating from Objective to Swift. 

Here you go:

Well, we started a new project and decided to bite the bullet and do it mainly using Swift (1.2). We’ve used a little Swift here and there - for example for writing XCUnit and KIF tests for existing projects. But making Swift the main language on a new project represents a significant commitment.

I say Swift is the ‘main language’ because of course, we’re using some third-party code that is written in Objective-C. There is no such thing as a pure Swift project.

The Problem

I hit a snag using mogenerator with Swift. For those unfamiliar with it - here’s elevator pitch from the GitHub README:

mogenerator is a command-line tool that, given an .xcdatamodel file, will generate two classes per entity. The first class, _MyEntity, is intended solely for machine consumption and will be continuously overwritten to stay in sync with your data model. The second class, MyEntity, subclasses _MyEntity, won't ever be overwritten and is a great place to put your custom logic.

 

While mogenerator does generate Swift code - I ran into a known issue getting that code to compile. I won't go into the details here - suffice it to say that the auto-generated Swift code wasn't compiling.  

The Solution

The solution I went with was to let mogenerator generate Objective-C instead, but threw away the mostly empty second class (‘MyEntity’ in the elevator pitch above). I created my own version of ‘MyEntity’ - in Swift - and subclassed the machine-generated _MyEntity. Frankly since I never touch the machine-generated class, I don’t really care if it’s written in C# (joke). The main thing is I can keep using mogenerator, while writing my custom-logic in Swift. The way Swift can interoperate with Objective-C makes this not only possible but almost trivially easy.

Win-win for everyone.

Richard Mischook

comments powered by Disqus