If you need to support deep links with a custom URL scheme in your iOS or tvOS app, check out my tidy little API to help convert URLs into deep link objects. It’s written in Swift 3. I published it on GitHub, right here:
Suppose you are working on a Swift program that needs a data model to represent a contact, such as a person from the user’s address book or a FaceBook friend. You might start off by modeling this as a Contact struct, like this:
This approach is simple but has a significant drawback. Notice how the Contact struct has two optional properties: phoneNumber and username. These properties are conditionally assigned a value, based on the contact type.
The rules for when each property should be nil are not obvious unless a developer happens to read the property comments. A design like this enables developers to make mistakes that could be easily avoided. It would be better if you could not accidentally access a property whose value is nil, because you forgot to check the contact type.
A common way to solve this problem in Swift is to create an enum:
The Contact enum has two cases. Each case has an associated struct value. When working with this enum it is impossible to accidentally access the wrong property, such as an AddressBook contact’s username, or a FaceBook contact’s phone number, because there are separate structs defined for each kind of contact. Those structs contain exactly the values relevant to their contact type. No need for optional properties. Hurrah!
However, there is also a drawback to this approach. In many cases it is convenient to access the properties common to each kind of contact in a uniform manner, like this:
To facilitate this, you could create computed properties on the Contact enum that read the corresponding property from each associated struct value in a switch block.
In this simple example the code above might not seem too bad. But in a realistic application where the data models have many properties, and there are many model entities to deal with, this type of code quickly becomes a tedious chore to write and maintain. Repetitive, boring code is a fertile source of bugs. There must be a better way…
This problem can be remedied through the use of Swift’s Mirror API. Mirrors are Swift’s way of allowing for introspective code; in other words, for code to reflect upon itself at run time. Compared to other platforms, like .NET or Java, a Mirror provides only very rudimentary reflection support, but it’s enough for our purposes here.
Let’s take a look at my ReflectableEnum protocol:
This protocol’s sole method has a default implementation provided by a protocol extension. It uses Mirrors to peek inside an enum instance and its associated struct in order to find the value of a property. This protocol can be used to alleviate the coding burden seen above, like so:
It’s important that the properties added to Contact have the exact same name as the properties they map to on the structs associated with the enum cases. The usage of Swift’s #function means that the name of the property which calls value(of:) is passed in as the propertyName argument.
The downside to this approach is that it is less safe. This relies on the use of naming conventions. It is not something the compiler can guarantee will work at run time. The implementation of the value(of:) method force-unwraps optional values in several places, which is a sign that this code is going to crash if things are not correctly set up. I want it to crash if it encounters a problem (such as if a struct does not have a property with a certain name and type), but that’s only necessary because the compiler cannot police this kind of code. If you prefer the comfort of knowing that the Swift compiler always has your back, this solution is not for you.
The code presented here is just a rough sketch. It might not meet the needs of your application, but it can be a simple starting point for further enhancements.
An Xcode playground containing the ReflectableEnum code is available here:
Here is my Swift 3 utility function for turning a live class/struct instance into Equatable protocol code for that type:
Here’s to never writing that kind of code ever again!
The way that functional programming languages allow functions to be combined can help make code easier to read and understand. The technique is known as function composition. I show how to compose functions in Swift 3 using custom operators, including a function composition operator that supports optional chaining semantics. It’s available in this GitHub repository:
The article can be read on that repository’s home page, and it’s also available in an Xcode playground. This allows you to experiment with the presented code and immediately see the results. Have fun!
This article presents a high-level overview of how my json2swift tool works.
Several people have expressed interest in using my code as the foundation for a similar tool, or just want to change the Swift code it generates, and have asked for guidance on how to get started. It’s a modest sized program, so this overview will be straightforward.
Here is a map of the pipeline in which JSON is transformed into Swift.
The user specifies a JSON file, represented by the top box in the diagram, when running json2swift on the command line. The JSON file data is read into memory and Apple’s JSONSerialization class tries to convert it into arrays, dictionaries, NSNumber‘s, etc.
Now things get interesting. The JSON objects are analyzed, using a process known as type inference, to create schemas which describe the JSON data entities. The data types that represent a JSON schema are defined here.
Analyzing a JSON document to infer its schema is handled here. However, one of the most useful aspects of json2swift is that it can combine evidence from multiple examples of an attribute, which I refer to as ‘attribute merging’ and have implemented here. An example of this functionality is shown in the Type Inference section of the repository’s README.
At this point the program has done nothing related to Swift whatsoever. If you want to use my JSON type inference engine for a different tool that generates code for languages other than Swift, there won’t be anything Swift-specific getting in your way.
The next step is to translate JSON schemas to data structures that represent the Swift code generated later on. Those abstractions of Swift types are defined in this file. Most of the translation logic is in here.
Last but not least the Swift model is used as a data source for SwiftCodeGenerator, as seen here. This is where you can tweak the tool’s generated Swift code. Once the Swift source code is generated, the tool writes it to a file with a .swift extension in the same directory as the input JSON file.
That’s all folks!
Ever since Swift was first released there has been an endless stream of new libraries to simplify writing Swift code that consumes JSON data. Since this is such a common and tedious aspect of developing apps, it’s an important topic to many Swift developers. In the Swift projects I’ve worked on, we have naturally gravitated toward an implementation pattern quite similar to the approach that Apple advocates. This style does not make use of a third-party library, and is reasonably simple and effective.
Regardless of which approach you take to writing code to consume JSON you still must spend time writing, testing, and fixing code. And let’s face it, writing code to turn JSON into data objects is grunt work. Boring, error-prone, grunt work. Ain’t nobody got time for that!
That’s why I created json2swift; a command line tool that writes your Swift code for you. You provide it with a sample of the JSON data your app consumes, it generates all the Swift code needed to consume that data. You just drop the generated Swift files into your project, rename and rearrange the shiny new code to your heart’s content, and move on to more interesting tasks.
But what about all those sweet JSON libraries that help you write code to turn JSON into Swift objects? Where do they fit in?
A fellow named Vivien recently opened an issue in my json2swift Github repository to ask what I thought about adding support for generating Swift code that uses the popular Unbox JSON library. I understood what he meant, but not why he would ask for such a thing. After a brief discussion, he and I came to an agreement that if you use json2swift there’s no need to continue using a third-party library to turn JSON into Swift data objects. There’s certainly no reason for the tool to generate code that uses a third-party JSON API!
For developers who are not accustomed to working with code generation tools, it might take some getting used to. Think about it this way…
If JSON libraries are a way to make yourself run faster; json2swift is a race car.
I published a tool that analyzes JSON data and generates Swift data model code, named json2swift. This tool helps eliminate most of the error-prone grunt work involved with consuming JSON data in a Swift app. The repository’s README has more details.
This has been an interesting project to work on, especially building a type inference engine, as described here.