Structures

The following structures are available globally.

  • This struct enables sequence-style enumeration for RLMObjects in Swift via RLMCollection.makeIterator

    See more

    Declaration

    Swift

    public struct RLMCollectionIterator : IteratorProtocol
  • This struct enables sequence-style enumeration for RLMDictionary in Swift via RLMDictionary.makeIterator

    See more

    Declaration

    Swift

    public struct RLMDictionaryIterator : IteratorProtocol
  • A Realm instance (also referred to as “a Realm”) represents a Realm database.

    Realms can either be stored on disk (see init(path:)) or in memory (see Configuration).

    Realm instances are cached internally, and constructing equivalent Realm objects (for example, by using the same path or identifier) produces limited overhead.

    If you specifically want to ensure a Realm instance is destroyed (for example, if you wish to open a Realm, check some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an autoreleasepool {} and ensure you have no other strong references to it.

    Warning

    warning Non-frozen RLMRealm instances are thread-confined and cannot be shared across threads or dispatch queues. Trying to do so will cause an exception to be thrown. You must obtain an instance of RLMRealm on each thread or queue you want to interact with the Realm on. Realms can be confined to a dispatch queue rather than the thread they are opened on by explicitly passing in the queue when obtaining the RLMRealm instance. If this is not done, trying to use the same instance in multiple blocks dispatch to the same queue may fail as queues are not always run on the same thread.
    See more

    Declaration

    Swift

    @frozen
    public struct Realm
    extension Realm: Equatable
  • LinkingObjects is an auto-updating container type. It represents zero or more objects that are linked to its owning model object through a property relationship.

    LinkingObjects can be queried with the same predicates as List<Element> and Results<Element>.

    LinkingObjects always reflects the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using for...in enumeration, which will always enumerate over the linking objects that were present when the enumeration is begun, even if some of them are deleted or modified to no longer link to the target object during the enumeration.

    LinkingObjects can only be used as a property on Object models. Properties of this type must be declared as let and cannot be dynamic.

    See more

    Declaration

    Swift

    @frozen
    public struct LinkingObjects<Element> : RealmCollectionImpl where Element : RLMObjectBase, Element : RealmCollectionValue
    extension LinkingObjects: RealmSubscribable
    extension LinkingObjects: LinkingObjectsProtocol

AddableType

  • Results is an auto-updating container type in Realm returned from object queries.

    Results can be queried with the same predicates as List<Element>, and you can chain queries to further filter query results.

    Results always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using for...in enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration.

    Results are lazily evaluated the first time they are accessed; they only run queries when the result of the query is requested. This means that chaining several temporary Results to sort and filter your data does not perform any unnecessary work processing the intermediate state.

    Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible.

    Results instances cannot be directly instantiated.

    See more

    Declaration

    Swift

    @frozen
    public struct Results<Element> : Equatable, RealmCollectionImpl where Element : RealmCollectionValue
    extension Results: RealmSubscribable
    extension Results: Encodable where Element: Encodable

Observation

  • A type-erased RealmCollection.

    Instances of RealmCollection forward operations to an opaque underlying collection having the same Element type. This type can be used to write non-generic code which can operate on or store multiple types of Realm collections. It does not have any runtime overhead over using the original collection directly.

    See more

    Declaration

    Swift

    @frozen
    public struct AnyRealmCollection<Element> : RealmCollectionImpl where Element : RealmCollectionValue
    extension AnyRealmCollection: RealmSubscribable
    extension AnyRealmCollection: Encodable where Element: Encodable
  • ProjectedCollection is a special type of collection for Projection’s properties which should be used when you want to project a List of Realm Objects to a list of values. You don’t need to instantiate this type manually. Use it by calling projectTo on a List property:

    class PersistedListObject: Object {
        @Persisted public var people: List<CommonPerson>
    }
    
    class ListProjection: Projection<PersistedListObject> {
        @Projected(\PersistedListObject.people.projectTo.firstName) var strings: ProjectedCollection<String>
    }
    
    See more

    Declaration

    Swift

    public struct ProjectedCollection<Element> : RandomAccessCollection, CustomStringConvertible, ThreadConfined where Element : RealmCollectionValue
  • CollectionElementMapper transforms the actual collection objects into a ProjectedCollection.

    For example:

     class Person: Object {
         @Persisted var dogs: List<Dog>
     }
     class PersonProjection: Projection<Person> {
         @Projected(\Person.dogs.projectTo.name) var dogNames: ProjectedCollection<String>
     }
    

    In this code the Person‘s dogs list will be prijected to the list of dogs names via projectTo

    Declaration

    Swift

    @dynamicMemberLookup
    public struct CollectionElementMapper<Element> where Element : RLMObjectBase, Element : RealmCollectionValue
  • Schema instances represent collections of model object schemas managed by a Realm.

    When using Realm, Schema instances allow performing migrations and introspecting the database’s schema.

    Schemas map to collections of tables in the core database.

    See more

    Declaration

    Swift

    @frozen
    public struct Schema : CustomStringConvertible
    extension Schema: Equatable
  • A SortDescriptor stores a key path and a sort order for use with sorted(sortDescriptors:). It is similar to NSSortDescriptor, but supports only the subset of functionality which can be efficiently run by Realm’s query engine.

    See more

    Declaration

    Swift

    @frozen
    public struct SortDescriptor
    extension SortDescriptor: CustomStringConvertible
    extension SortDescriptor: Equatable
    extension SortDescriptor: ExpressibleByStringLiteral

Subscriptions

  • A subscription which wraps a Realm notification.

    See more

    Declaration

    Swift

    @available(macOS 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, macOSApplicationExtension 10.15, tvOS 13.0, *)
    @frozen
    public struct ObservationSubscription : Subscription
  • A subscription which wraps a Realm AsyncOpenTask.

    See more

    Declaration

    Swift

    @available(macOS 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, macOSApplicationExtension 10.15, tvOS 13.0, *)
    @frozen
    public struct AsyncOpenSubscription : Subscription
  • Realm event recording can be used to record all reads and writes performed on a Realm and report them to the server. Enable event recording by setting the eventConfiguration property of the Realm.Configuration used to open a Realm, and then obtain an Events instance with the events property on the Realm.

    See more

    Declaration

    Swift

    public struct Events
  • Configuration parameters for Realm event recording.

    Enabling Realm event recording is done by setting Realm.Configuration.eventConfiguration to any non-nil EventConfiguration. A default-initialized configuration is valid, but some properties may need to be customized.

    Using Realm event recording requires including the collection AuditEvent in your schema defined on the server for the App which you will be writing events to. The schema must contain the following fields:

    • _id: ObjectId
    • activity: String
    • event: String?
    • data: String?
    • timestamp: Date In addition, there must be a String? field for each metadata key used.
    See more

    Declaration

    Swift

    @frozen
    public struct EventConfiguration

MapIndex

SingleMapEntry

  • Container for holding a single key-value entry in a Map. This is used where a tuple cannot be expressed as a generic argument.

    See more

    Declaration

    Swift

    public struct SingleMapEntry<Key, Value> : _RealmMapValue, Hashable where Key : _MapKey, Value : RealmCollectionValue
  • Migration instances encapsulate information intended to facilitate a schema migration.

    A Migration instance is passed into a user-defined MigrationBlock block when updating the version of a Realm. This instance provides access to the old and new database schemas, the objects in the Realm, and provides functionality for modifying the Realm during the migration.

    See more

    Declaration

    Swift

    @frozen
    public struct Migration
  • Information about a specific property which changed in an Object change notification.

    See more

    Declaration

    Swift

    @frozen
    public struct PropertyChange
  • This class represents Realm model object schemas.

    When using Realm, ObjectSchema instances allow performing migrations and introspecting the database’s schema.

    Object schemas map to tables in the core database.

    See more

    Declaration

    Swift

    @frozen
    public struct ObjectSchema : CustomStringConvertible
    extension ObjectSchema: Equatable
  • @Persisted is used to declare properties on Object subclasses which should be managed by Realm.

    Example of usage:

    class MyModel: Object {
        // A basic property declaration. A property with no
        // default value supplied will default to `nil` for
        // Optional types, zero for numeric types, false for Bool,
        // an empty string/data, and a new random value for UUID
        // and ObjectID.
        @Persisted var basicIntProperty: Int
    
        // Custom default values can be specified with the
        // standard Swift syntax
        @Persisted var intWithCustomDefault: Int = 5
    
        // Properties can be indexed by passing `indexed: true`
        // to the initializer.
        @Persisted(indexed: true) var indexedString: String
    
        // Properties can set as the class's primary key by
        // passing `primaryKey: true` to the initializer
        @Persisted(primaryKey: true) var _id: ObjectId
    
        // List and set properties should always be declared
        // with `: List` rather than `= List()`
        @Persisted var listProperty: List<Int>
        @Persisted var setProperty: MutableSet<MyObject>
    
        // LinkingObjects properties require setting the source
        // object link property name in the initializer
        @Persisted(originProperty: "outgoingLink")
        var incomingLinks: LinkingObjects<OtherModel>
    
        // Properties which are not marked with @Persisted will
        // be ignored entirely by Realm.
        var ignoredProperty = true
    }
    

    Int, Bool, String, ObjectId and Date properties can be indexed by passing indexed: true to the initializer. Indexing a property improves the performance of equality queries on that property, at the cost of slightly worse write performance. No other operations currently use the index.

    A property can be set as the class’s primary key by passing primaryKey: true to the initializer. Compound primary keys are not supported, and setting more than one property as the primary key will throw an exception at runtime. Only Int, String, UUID and ObjectID properties can be made the primary key, and when using Atlas App Services, the primary key must be named _id. The primary key property can only be mutated on unmanaged objects, and mutating it on an object which has been added to a Realm will throw an exception.

    Properties can optionally be given a default value using the standard Swift syntax. If no default value is given, a value will be generated on first access: nil for all Optional types, zero for numeric types, false for Bool, an empty string/data, and a new random value for UUID and ObjectID. List and MutableSet properties should not be defined by setting them to a default value of an empty List/MutableSet. Doing so will work, but will result in worse performance when accessing objects managed by a Realm. Similarly, ObjectID properties should not be initialized to ObjectID.generate(), as doing so will result in extra ObjectIDs being generated and then discarded when reading from a Realm.

    If a class has at least one @Persisted property, all other properties will be ignored by Realm. This means that they will not be persisted and will not be usable in queries and other operations such as sorting and aggregates which require a managed property.

    @Persisted cannot be used anywhere other than as a property on an Object or EmbeddedObject subclass and trying to use it in other places will result in runtime errors.

    See more

    Declaration

    Swift

    @propertyWrapper
    public struct Persisted<Value> where Value : _Persistable
    extension Persisted: Decodable where Value: Decodable
    extension Persisted: Encodable where Value: Encodable
    extension Persisted: OptionalCodingWrapper where Value: ExpressibleByNilLiteral

Projection

  • @Projected is used to declare properties on Projection protocols which should be managed by Realm.

    Example of usage:

    public class Person: Object {
        @Persisted var firstName = ""
        @Persisted var lastName = ""
        @Persisted var address: Address? = nil
        @Persisted var friends = List<Person>()
        @Persisted var reviews = List<String>()
    }
    
    class PersonProjection: Projection<Person> {
        @Projected(\Person.firstName) var firstName
        @Projected(\Person.lastName.localizedUppercase) var lastNameCaps
        @Projected(\Person.address.city) var homeCity
        @Projected(\Person.friends.projectTo.firstName) var firstFriendsName: ProjectedCollection<String>
    }
    
    let people: Results<PersonProjection> = realm.objects(PersonProjection.self)
    
    See more

    Declaration

    Swift

    @propertyWrapper
    public struct Projected<T, Value> : AnyProjected where T : RLMObjectBase

ProjectionOservable

  • Information about a specific property which changed in an Object change notification.

    See more

    Declaration

    Swift

    @frozen
    public struct ProjectedPropertyChange
  • Property instances represent properties managed by a Realm in the context of an object schema. Such properties may be persisted to a Realm file or computed from other data in the Realm.

    When using Realm, property instances allow performing migrations and introspecting the database’s schema.

    Property instances map to columns in the core database.

    See more

    Declaration

    Swift

    @frozen
    public struct Property : CustomStringConvertible
    extension Property: Equatable
  • Enum representing an option for String queries.

    See more

    Declaration

    Swift

    public struct StringOptions : OptionSet
  • Query is a class used to create type-safe query predicates.

    With Query you are given the ability to create Swift style query expression that will then be constructed into an NSPredicate. The Query class should not be instantiated directly and should be only used as a paramater within a closure that takes a query expression as an argument. Example:

    public func where(_ query: ((Query<Element>) -> Query<Element>)) -> Results<Element>
    

    You would then use the above function like so:

    let results = realm.objects(Person.self).query {
       $0.name == "Foo" || $0.name == "Bar" && $0.age >= 21
    }
    

    Supported predicate types

    Prefix

    • NOT ! swift let results = realm.objects(Person.self).query { !$0.dogsName.contains("Fido") || !$0.name.contains("Foo") }

    Comparisions

    • Equals ==
    • Not Equals !=
    • Greater Than >
    • Less Than <
    • Greater Than or Equal >=
    • Less Than or Equal <=
    • Between .contains(_ range:)

    Collections

    • IN .contains(_ element:)
    • Between .contains(_ range:)

    Map

    • @allKeys .keys
    • @allValues .values

    Compound

    • AND &&
    • OR ||

    Collection Aggregation

    • @avg .avg
    • @min .min
    • @max .max
    • @sum .sum
    • @count .count swift let results = realm.objects(Person.self).query { !$0.dogs.age.avg >= 0 || !$0.dogsAgesArray.avg >= 0 }

    Other

    • NOT !
    • Subquery ($0.fooList.intCol >= 5).count > n
    See more

    Declaration

    Swift

    @dynamicMemberLookup
    public struct Query<T>
  • An iterator for a RealmCollection instance.

    See more

    Declaration

    Swift

    @frozen
    public struct RLMIterator<Element> : IteratorProtocol where Element : RealmCollectionValue
  • An iterator for a RealmKeyedCollection instance.

    See more

    Declaration

    Swift

    @frozen
    public struct RLMMapIterator<Element> : IteratorProtocol where Element : _RealmMapValue
  • An iterator for Map<Key, Value> which produces (key: Key, value: Value) pairs for each entry in the map.

    See more

    Declaration

    Swift

    @frozen
    public struct RLMKeyValueIterator<Key, Value> : IteratorProtocol where Key : _MapKey, Value : RealmCollectionValue

StateRealmObject

  • A property wrapper type that instantiates an observable object.

    Create a state realm object in a SwiftUI/View, SwiftUI/App, or SwiftUI/Scene by applying the @StateRealmObject attribute to a property declaration and providing an initial value that conforms to the doc://com.apple.documentation/documentation/Combine/ObservableObject protocol:

    @StateRealmObject var model = DataModel()
    

    SwiftUI creates a new instance of the object only once for each instance of the structure that declares the object. When published properties of the observable realm object change, SwiftUI updates the parts of any view that depend on those properties. If unmanaged, the property will be read from the object itself, otherwise, it will be read from the underlying Realm. Changes to the value will update the view asynchronously:

    Text(model.title) // Updates the view any time `title` changes.
    

    You can pass the state object into a property that has the SwiftUI/ObservedRealmObject attribute.

    Get a SwiftUI/Binding to one of the state object’s properties using the $ operator. Use a binding when you want to create a two-way connection to one of the object’s properties. For example, you can let a SwiftUI/Toggle control a Boolean value called isEnabled stored in the model:

    Toggle("Enabled", isOn: $model.isEnabled)
    

    This will write the modified isEnabled property to the model object’s Realm.

    See more

    Declaration

    Swift

    @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
    @propertyWrapper
    public struct StateRealmObject<T> : DynamicProperty where T : RealmSubscribable, T : ThreadConfined, T : Equatable

ObservedResults

  • A property wrapper type that represents the results of a query on a realm.

    The results use the realm configuration provided by the environment value realmConfiguration.

    Unlike non-SwiftUI results collections, the ObservedResults is mutable. Writes to an ObservedResults collection implicitly perform a write transaction. If you add an object to the ObservedResults that the associated query would filter out, the object is added to the realm but not included in the ObservedResults.

    Given @ObservedResults var v in SwiftUI, $v refers to a BoundCollection.

    See more

    Declaration

    Swift

    @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
    @propertyWrapper
    public struct ObservedResults<ResultType> : DynamicProperty, BoundCollection where ResultType : KeypathSortable, ResultType : RealmFetchable, ResultType : _ObservedResultsValue, ResultType : Identifiable

ObservedRealmObject

  • A property wrapper type that subscribes to an observable Realm Object or List and invalidates a view whenever the observable object changes.

    See more

    Declaration

    Swift

    @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
    @propertyWrapper
    public struct ObservedRealmObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject, ObjectType : RealmSubscribable, ObjectType : ThreadConfined, ObjectType : Equatable

AsyncOpen

  • A property wrapper type that initiates a Realm.asyncOpen() for the current user which asynchronously open a Realm, and notifies states for the given process

    Add AsyncOpen to your SwiftUI/View or SwiftUI/App, after a user is already logged in, or if a user is going to be logged in

    @AsyncOpen(appId: "app_id", partitionValue: <partition_value>) var asyncOpen
    

    This will immediately initiates a Realm.asyncOpen() operation which will perform all work needed to get the Realm to a usable state. (see Realm.asyncOpen() documentation)

    This property wrapper will publish states of the current Realm.asyncOpen() process like progress, errors and an opened realm, which can be used to update the view

    struct AsyncOpenView: View {
        @AsyncOpen(appId: "app_id", partitionValue: <partition_value>) var asyncOpen
    
        var body: some View {
           switch asyncOpen {
           case .notOpen:
               ProgressView()
           case .open(let realm):
               ListView()
                  .environment(\.realm, realm)
           case .error(_):
               ErrorView()
           case .progress(let progress):
               ProgressView(progress)
           }
        }
    }
    

    This opened realm can be later injected to the view as an environment value which will be used by our property wrappers to populate the view with data from the opened realm

    ListView()
       .environment(\.realm, realm)
    
    See more

    Declaration

    Swift

    @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
    @propertyWrapper
    public struct AsyncOpen : DynamicProperty

AutoOpen

  • AutoOpen will try once to asynchronously open a Realm, but in case of no internet connection will return an opened realm for the given appId and partitionValue which can be used within our view. Add AutoOpen to your SwiftUI/View or SwiftUI/App, after a user is already logged in or if a user is going to be logged in

    @AutoOpen(appId: "app_id", partitionValue: <partition_value>, timeout: 4000) var autoOpen
    

    This will immediately initiates a Realm.asyncOpen() operation which will perform all work needed to get the Realm to a usable state. (see Realm.asyncOpen() documentation)

    This property wrapper will publish states of the current Realm.asyncOpen() process like progress, errors and an opened realm, which can be used to update the view

    struct AutoOpenView: View {
        @AutoOpen(appId: "app_id", partitionValue: <partition_value>) var autoOpen
    
        var body: some View {
           switch autoOpen {
           case .notOpen:
               ProgressView()
           case .open(let realm):
               ListView()
                  .environment(\.realm, realm)
           case .error(_):
               ErrorView()
           case .progress(let progress):
               ProgressView(progress)
           }
        }
    }
    

    This opened realm can be later injected to the view as an environment value which will be used by our property wrappers to populate the view with data from the opened realm

    ListView()
       .environment(\.realm, realm)
    

    This property wrapper behaves similar as AsyncOpen, and in terms of declaration and use is completely identical, but with the difference of a offline-first approach.

    See more

    Declaration

    Swift

    @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
    @propertyWrapper
    public struct AutoOpen : DynamicProperty
  • A SyncConfiguration represents configuration parameters for Realms intended to sync with Atlas App Services.

    See more

    Declaration

    Swift

    @frozen
    public struct SyncConfiguration
  • Structure providing an interface to call an Atlas App Services function with the provided name and arguments.

    user.functions.sum([1, 2, 3, 4, 5]) { sum, error in
        guard case let .int64(value) = sum else {
            print(error?.localizedDescription)
        }
    
        assert(value == 15)
    }
    

    The dynamic member name (sum in the above example) is directly associated with the function name. The first argument is the BSONArray of arguments to be provided to the function. The second and final argument is the completion handler to call when the function call is complete. This handler is executed on a non-main global DispatchQueue.

    See more

    Declaration

    Swift

    @dynamicMemberLookup
    @frozen
    public struct Functions
  • Structure enabling the following syntactic sugar for user functions:

    guard case let .int32(sum) = try await user.functions.sum([1, 2, 3, 4, 5]) else {
       return
    }
    

    The dynamic member name (sum in the above example) is provided by @dynamicMemberLookup which is directly associated with the function name.

    See more

    Declaration

    Swift

    @dynamicCallable
    public struct FunctionCallable
  • SyncSubscription is used to define a Flexible Sync subscription obtained from querying a subscription set, which can be used to read or remove/update a committed subscription.

    See more

    Declaration

    Swift

    @frozen
    public struct SyncSubscription
  • SubscriptionQuery is used to define an named/unnamed query subscription query, which can be added/remove or updated within a write subscription transaction.

    See more

    Declaration

    Swift

    @frozen
    public struct QuerySubscription<T> where T : RealmSwiftObject
  • SyncSubscriptionSet is a collection of SyncSubscriptions. This is the entry point for adding and removing SyncSubscriptions.

    See more

    Declaration

    Swift

    @frozen
    public struct SyncSubscriptionSet
    extension SyncSubscriptionSet: Sequence
  • This struct enables sequence-style enumeration for SyncSubscriptionSet.

    See more

    Declaration

    Swift

    @frozen
    public struct SyncSubscriptionSetIterator : IteratorProtocol
  • An object intended to be passed between threads containing a thread-safe reference to its thread-confined object.

    To resolve a thread-safe reference on a target Realm on a different thread, pass to Realm.resolve(_:).

    Warning

    A ThreadSafeReference object must be resolved at most once. Failing to resolve a ThreadSafeReference will result in the source version of the Realm being pinned until the reference is deallocated.

    Note

    Prefer short-lived ThreadSafeReferences as the data for the version of the source Realm will be retained until all references have been resolved or deallocated.

    See more

    Declaration

    Swift

    @frozen
    public struct ThreadSafeReference<Confined> where Confined : ThreadConfined
    extension ThreadSafeReference: Sendable