CustomPersistable

A type which can be mapped to and from a type which Realm supports.

To store types in a Realm which Realm doesn’t natively support, declare the type as conforming to either CustomPersistable or FailableCustomPersistable. This requires defining an associatedtype named PersistedType which indicates what Realm type this type will be mapped to, an initializer taking the PersistedType, and a property which returns the appropriate PersistedType. For example, to make URL persistable:

// Not all strings are valid URLs, so this uses
// FailableCustomPersistable to handle the case when the data
// in the Realm isn't a valid URL.
extension URL: FailableCustomPersistable {
    typealias PersistedType = String
    init?(persistedValue: String) {
        self.init(string: persistedValue)
    }
    var persistableValue: PersistedType {
        self.absoluteString
    }
}

After doing this, you can define properties using URL:

class MyModel: Object {
    @Persisted var url: URL
    @Persisted var mapOfUrls: Map<String, URL>
}

PersistedType can be any of the primitive types supported by Realm or an EmbeddedObject subclass. EmbeddedObject subclasses can be used if you need to store more than one piece of data for your mapped type. For example, to store CGPoint:

// Define the storage object. A type used for custom mappings
// does not have to be used exclusively for custom mappings,
// and more than one type can map to a single embedded object
// type.
class CGPointObject: EmbeddedObject {
    @Persisted var double: x
    @Persisted var double: y
}

// Define the mapping. This mapping isn't failable, as the
// data stored in the Realm can always be interpreted as a
// CGPoint.
extension CGPoint: CustomPersistable {
    typealias PersistedType = CGPointObject
    init(persistedValue: CGPointObject) {
        self.init(x: persistedValue.x, y: persistedValue.y)
    }
    var persistableValue: PersistedType {
        CGPointObject(value: [x, y])
    }
}

class PointModel: Object {
    // Note that types which are mapped to embedded objects do
    // not have to be optional (but can be).
    @Persisted var point: CGPoint
    @Persisted var line: List<CGPoint>
}

Queries are performed on the persisted type and not the custom persistable type. Values passed into queries can be of either the persisted type or custom persistable type. For custom persistable types which map to embedded objects, memberwise equality will be used. For examples, realm.objects(PointModel.self).where { $0.point == CGPoint(x: 1, y: 2) } is equivalent to "point.x == 1 AND point.y == 2".