Rate this tutorial
A typical design pattern is to persist data using types natively supported by Realm, and then use a richer set of types in your app. When reading data, you add extra boilerplate code to convert them to your app's types. When persisting data, you add more boilerplate code to convert your data back into types supported by Realm.
That works fine and gives you complete control over the type conversions. The downside is that you can end up with dozens of places in your code where you need to make the conversion.
Type projections still give you total control over how to map a
CGPointinto something that can be persisted in Realm. But, you write the conversion code just once and then forget about it. The Realm-Swift SDK will then ensure that types are converted back and forth as required in the rest of your app.
The Realm-Swift SDK enables this by adding two new protocols that you can use to extend any Swift type. You opt whether to implement
CustomPersistableor the version that's allowed to fail (
It's currently iOS-only, but it would also sync with any Android drawing app that is connected to the same Realm back end.
The Realm-Drawing iOS app uses three types that aren't natively supported by Realm:
In this section, you'll see how simple it is to use type projections to convert them into types that can be persisted to Realm and synced.
Lineclass that uses the non-Realm-native types.
Let's see how each type is handled.
CGFloatto conform to Realm-Swift's
CustomPersistableprotocol. All I needed to provide was:
- An initializer to convert what's persisted in Realm (a
Double) into the
CGFloatused by the model
- A method to convert a
I implement the
CGPointby mapping between a
ycoordinates within a
The extension to implement
Colorprovides methods to initialize
PersistableColor, and to generate a
Type projections provide a simple, elegant way to convert any type to types that can be persisted and synced by Realm.
It's your responsibility to define how the mapping is implemented. After that, the Realm SDK takes care of everything else.
News & Announcements
Realm Cocoa 5.0 - Multithreading Support with Integration for SwiftUI & Combine
Oct 19, 2022