New article – Realm-Swift Type Projections

Realm natively provides a broad set of data types, including Bool, Int, Float, Double, String, Date, ObjectID, List, Mutable Set, enum, Map, …

But, there are other data types that many of your iOS apps are likely to use. As an example, if you’re using Core Graphics, then it’s hard to get away without using types such as CGFloat, CGPoint, etc. When working with SwiftUI, you use the Color struct when working with colors.

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.

Realm-Swift Type Projections still give you total control over how to map a CGPoint into 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 CustomPersistable or the version that’s allowed to fail (FailableCustomPersistable):

protocol CustomPersistable {
   associatedtype PersistedType
   init(persisted: PersistedType)
   var persistableValue: PersistedType { get }
}
protocol FailableCustomPersistable {
   associatedtype PersistedType
   init?(persisted: PersistedType)
   var persistableValue: PersistedType { get }
}

In Realm-Swift Type Projections, I’ll show how the Realm-Drawing app uses type projections to interface between Realm and Core Graphics.