HomeLearnHow-toRealm-Swift Type Projections

Realm-Swift Type Projections

Updated: Feb 24, 2022 |

Published: Jan 26, 2022

  • Mobile
  • Realm
  • Swift
  • ...

By Andrew Morgan

Rate this article

#Introduction

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.

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):

1protocol CustomPersistable {
2 associatedtype PersistedType
3 init(persisted: PersistedType)
4 var persistableValue: PersistedType { get }
5}
6protocol FailableCustomPersistable {
7 associatedtype PersistedType
8 init?(persisted: PersistedType)
9 var persistableValue: PersistedType { get }
10}

In this post, I'll show how the Realm-Drawing app uses type projections to interface between Realm and Core Graphics.

#Prerequisites

#The Realm-Drawing App

Realm-Drawing is a simple, collaborative drawing app. If two people log into the app using the same username, they can work on a drawing together. All strokes making up the drawing are persisted to Realm and then synced to all other instances of the app where the same username is logged in.

Animated screen captures showing two iOS devices working on the same drawing

It's currently iOS-only, but it would also sync with any Android drawing app that is connected to the same Realm back end.

#Using Type Projections in the App

The Realm-Drawing iOS app uses three types that aren't natively supported by Realm:

  • CGFloat
  • CGPoint
  • Color (SwiftUI)

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.

#Realm Schema (The Model)

An individual drawing is represented by a single Drawing object:

1class Drawing: Object, ObjectKeyIdentifiable {
2 @Persisted(primaryKey: true) var _id: ObjectId
3 @Persisted var name = UUID().uuidString
4 @Persisted var lines = RealmSwift.List<Line>()
5}

A Drawing contains a List of Line objects:

1class Line: EmbeddedObject, ObjectKeyIdentifiable {
2 @Persisted var lineColor: Color
3 @Persisted var lineWidth: CGFloat = 5.0
4 @Persisted var linePoints = RealmSwift.List<CGPoint>()
5}

It's the Line class that uses the non-Realm-native types.

Let's see how each type is handled.

#CGFloat

I extend CGFloat to conform to Realm-Swift's CustomPersistable protocol. All I needed to provide was:

  • An initializer to convert what's persisted in Realm (a Double) into the CGFloat used by the model
  • A method to convert a CGFloat into a Double:
1extension CGFloat: CustomPersistable {
2 public typealias PersistedType = Double
3 public init(persistedValue: Double) { self.init(persistedValue) }
4 public var persistableValue: Double { Double(self) }
5}

The view can then use lineWidth from the model object without worrying about how it's converted by the Realm SDK:

1context.stroke(path, with: .color(line.lineColor),
2 style: StrokeStyle(
3 lineWidth: line.lineWidth,
4 lineCap: .round, l
5 ineJoin: .round
6 )
7)

#CGPoint

CGPoint is a little trickier, as it can't just be cast into a Realm-native type. CGPoint contains the x and y coordinates for a point, and so, I create a Realm-friendly class (PersistablePoint) that stores just that—x and y values as Doubles:

1public class PersistablePoint: EmbeddedObject, ObjectKeyIdentifiable {
2 @Persisted var x = 0.0
3 @Persisted var y = 0.0
4
5 convenience init(_ point: CGPoint) {
6 self.init()
7 self.x = point.x
8 self.y = point.y
9 }
10}

I implement the CustomPersistable protocol for CGPoint by mapping between a CGPoint and the x and y coordinates within a PersistablePoint:

1extension CGPoint: CustomPersistable {
2 public typealias PersistedType = PersistablePoint
3 public init(persistedValue: PersistablePoint) { self.init(x: persistedValue.x, y: persistedValue.y) }
4 public var persistableValue: PersistablePoint { PersistablePoint(self) }
5}

#SwiftUI.Color

Color is made up of the three RGB components plus the opacity. I use the PersistableColor class to persist a representation of Color:

1public class PersistableColor: EmbeddedObject {
2 @Persisted var red: Double = 0
3 @Persisted var green: Double = 0
4 @Persisted var blue: Double = 0
5 @Persisted var opacity: Double = 0
6
7 convenience init(color: Color) {
8 self.init()
9 if let components = color.cgColor?.components {
10 if components.count >= 3 {
11 red = components[0]
12 green = components[1]
13 blue = components[2]
14 }
15 if components.count >= 4 {
16 opacity = components[3]
17 }
18 }
19 }
20}

The extension to implement CustomPersistable for Color provides methods to initialize Color from a PersistableColor, and to generate a PersistableColor from itself:

1extension Color: CustomPersistable {
2 public typealias PersistedType = PersistableColor
3
4 public init(persistedValue: PersistableColor) { self.init(
5 .sRGB,
6 red: persistedValue.red,
7 green: persistedValue.green,
8 blue: persistedValue.blue,
9 opacity: persistedValue.opacity) }
10
11 public var persistableValue: PersistableColor {
12 PersistableColor(color: self)
13 }
14}

The view can then use selectedColor from the model object without worrying about how it's converted by the Realm SDK:

1context.stroke(
2 path,
3 with: .color(line.lineColor),
4 style: StrokeStyle(lineWidth:
5 line.lineWidth,
6 lineCap: .round,
7 lineJoin: .round)
8)

#Conclusion

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.

Please provide feedback and ask any questions in the Realm Community Forum.

Rate this article
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.