Map

public final class Map<Key, Value> : RLMSwiftCollectionBase where Key : _MapKey, Value : RealmCollectionValue
extension Map: ObservableObject, RealmSubscribable
extension Map: Sequence
extension Map: RealmKeyedCollection
extension Map: Decodable where Key: Decodable, Value: Decodable
extension Map: Encodable where Key: Encodable, Value: Encodable

Map is a key-value storage container used to store supported Realm types.

Map is a generic type that is parameterized on the type it stores. This can be either an Object subclass or one of the following types: Bool, Int, Int8, Int16, Int32, Int64, Float, Double, String, Data, Date, Decimal128, and ObjectId (and their optional versions)

Note

Optional versions of the above types except Object are only supported in non-synchronized Realms.

Map only supports String as a key. Realm disallows the use of . or $ characters within a dictionary key.

Unlike Swift’s native collections, Maps is a reference types, and are only immutable if the Realm that manages them is opened as read-only.

A Map can be filtered and sorted with the same predicates as Results<Value>.

Properties

  • The Realm which manages the map, or nil if the map is unmanaged.

    Declaration

    Swift

    public var realm: Realm? { get }
  • Indicates if the map can no longer be accessed.

    Declaration

    Swift

    public var isInvalidated: Bool { get }
  • Returns all of the keys in this map.

    Declaration

    Swift

    public var keys: [Key] { get }
  • Returns all of the values in this map.

    Declaration

    Swift

    public var values: [Value] { get }

Initializers

  • Creates a Map that holds Realm model objects of type Value.

    Declaration

    Swift

    public override init()

Count

  • Returns the number of key-value pairs in this map.

    Declaration

    Swift

    @objc
    public var count: Int { get }

Mutation

  • Updates the value stored in the map for the given key, or adds a new key-value pair if the key does not exist.

    Note

    If the value being added to the map is an unmanaged object and the map is managed then that unmanaged object will be added to the Realm.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func updateValue(_ value: Value, forKey key: Key)

    Parameters

    value

    a value’s key path predicate.

    forKey

    The direction to sort in.

  • Merges the given dictionary into this map, using a combining closure to determine the value for any duplicate keys.

    If dictionary contains a key which is already present in this map, combine will be called with the value currently in the map and the value in the dictionary. The value returned by the closure will be stored in the map for that key.

    Note

    If a value being added to the map is an unmanaged object and the map is managed then that unmanaged object will be added to the Realm.

    Warning

    This method may only be called on managed Maps during a write transaction.

    Declaration

    Swift

    public func merge<S>(_ sequence: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows
            where S: Sequence, S.Element == (key: Key, value: Value)

    Parameters

    dictionary

    The dictionary to merge into this map.

    combine

    A closure that takes the current and new values for any duplicate keys. The closure returns the desired value for the final map.

  • Merges the given map into this map, using a combining closure to determine the value for any duplicate keys.

    If other contains a key which is already present in this map, combine will be called with the value currently in the map and the value in the other map. The value returned by the closure will be stored in the map for that key.

    Note

    If a value being added to the map is an unmanaged object and the map is managed then that unmanaged object will be added to the Realm.

    Warning

    This method may only be called on managed Maps during a write transaction.

    Declaration

    Swift

    public func merge(_ other: Map<Key, Value>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows

    Parameters

    other

    The map to merge into this map.

    combine

    A closure that takes the current and new values for any duplicate keys. The closure returns the desired value for the final map.

  • Removes the given key and its associated object, only if the key exists in the map. If the key does not exist, the map will not be modified.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func removeObject(for key: Key)
  • Removes all objects from the map. The objects are not removed from the Realm that manages them.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func removeAll()
  • Returns the value for a given key, or sets a value for a key should the subscript be used for an assign.

    Note

    Note:If the value being added to the map is an unmanaged object and the map is managed then that unmanaged object will be added to the Realm.

    Note

    Note:If the value being assigned for a key is nil then that key will be removed from the map.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public subscript(key: Key) -> Value? { get set }

    Parameters

    key

    The key.

  • Returns a type of AnyObject for a specified key if it exists in the map.

    Declaration

    Swift

    @objc
    public func object(forKey key: AnyObject) -> AnyObject?

    Parameters

    key

    The key to the property whose values are desired.

KVC

  • Returns a type of Value for a specified key if it exists in the map.

    Note that when using key-value coding, the key must be a string.

    Declaration

    Swift

    @nonobjc
    public func value(forKey key: String) -> AnyObject?

    Parameters

    key

    The key to the property whose values are desired.

  • Returns a type of Value for a specified key if it exists in the map.

    Declaration

    Swift

    @nonobjc
    public func value(forKeyPath keyPath: String) -> AnyObject?

    Parameters

    keyPath

    The key to the property whose values are desired.

  • Adds a given key-value pair to the map or updates a given key should it already exist.

    Warning

    This method can only be called during a write transaction.

    Declaration

    Swift

    public func setValue(_ value: Any?, forKey key: String)

    Parameters

    value

    The object value.

    key

    The name of the property whose value should be set on each object.

Filtering

  • Returns a Results containing all matching values in the map with the given predicate.

    Note

    This will return the values in the map, and not the key-value pairs.

    Declaration

    Swift

    public func filter(_ predicate: NSPredicate) -> Results<Value>

    Parameters

    predicate

    The predicate with which to filter the values.

  • Returns a Results containing all matching values in the map with the given query.

    Note

    This should only be used with classes using the @Persistable property declaration.

    • Usage:

      myMap.where {
      ($0.fooCol > 5) && ($0.barCol == "foobar")
      }
      

    Note

    See Query for more information on what query operations are available.

    Declaration

    Swift

    public func `where`(_ isIncluded: ((Query<Value>) -> Query<Bool>)) -> Results<Value>

    Parameters

    isIncluded

    The query closure with which to filter the objects.

  • Returns a Boolean value indicating whether the Map contains the key-value pair satisfies the given predicate

    Declaration

    Swift

    public func contains(where predicate: @escaping (_ key: Key, _ value: Value) -> Bool) -> Bool

    Parameters

    where

    a closure that test if any key-pair of the given map represents the match.

Sorting

  • Returns a Results containing the objects in the map, but sorted.

    Objects are sorted based on their values. For example, to sort a map of Dates from newest to oldest based, you might call dates.sorted(ascending: true).

    Declaration

    Swift

    public func sorted(ascending: Bool = true) -> Results<Value>

    Parameters

    ascending

    The direction to sort in.

  • Returns a Results containing the objects in the map, but sorted.

    Objects are sorted based on the values of the given key path. For example, to sort a map of Students from youngest to oldest based on their age property, you might call students.sorted(byKeyPath: "age", ascending: true).

    Warning

    Dictionaries may only be sorted by properties of boolean, Date, NSDate, single and double-precision floating point, integer, and string types.

    Declaration

    Swift

    public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Value>

    Parameters

    keyPath

    The key path to sort by.

    ascending

    The direction to sort in.

  • Returns a Results containing the objects in the map, but sorted.

    Warning

    Map’s may only be sorted by properties of boolean, Date, NSDate, single and double-precision floating point, integer, and string types.

    Declaration

    Swift

    public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Value>
        where S.Iterator.Element == SortDescriptor

Aggregate Operations

  • Returns the minimum (lowest) value of the given property among all the objects in the collection, or nil if the map is empty.

    Warning

    Only a property whose type conforms to the MinMaxType protocol can be specified.

    Declaration

    Swift

    public func min<T>(ofProperty property: String) -> T? where T : _HasPersistedType, T.PersistedType : MinMaxType

    Parameters

    property

    The name of a property whose minimum value is desired.

  • Returns the maximum (highest) value of the given property among all the objects in the collection, or nil if the map is empty.

    Warning

    Only a property whose type conforms to the MinMaxType protocol can be specified.

    Declaration

    Swift

    public func max<T>(ofProperty property: String) -> T? where T : _HasPersistedType, T.PersistedType : MinMaxType

    Parameters

    property

    The name of a property whose minimum value is desired.

  • Returns the sum of the given property for objects in the collection, or nil if the map is empty.

    Warning

    Only names of properties of a type conforming to the AddableType protocol can be used.

    Declaration

    Swift

    public func sum<T>(ofProperty property: String) -> T where T : _HasPersistedType, T.PersistedType : AddableType

    Parameters

    property

    The name of a property conforming to AddableType to calculate sum on.

  • Returns the average value of a given property over all the objects in the collection, or nil if the map is empty.

    Warning

    Only a property whose type conforms to the AddableType protocol can be specified.

    Declaration

    Swift

    public func average<T>(ofProperty property: String) -> T? where T : _HasPersistedType, T.PersistedType : AddableType

    Parameters

    property

    The name of a property whose values should be summed.

Notifications

  • Registers a block to be called each time the map changes.

    The block will be asynchronously called with the initial map, and then called again after each write transaction which changes either any of the keys or values in the map.

    The change parameter that is passed to the block reports, in the form of keys within the map, which of the key-value pairs were added, removed, or modified during each write transaction.

    If no queue is given, notifications are delivered via the standard run loop, and so can’t be delivered while the run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When notifications can’t be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection.

    For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction.

    let myStringMap = myObject.stringMap
    print("myStringMap.count: \(myStringMap?.count)") // => 0
    let token = myStringMap.observe { changes in
        switch changes {
        case .initial(let myStringMap):
            // Will print "myStringMap.count: 1"
            print("myStringMap.count: \(myStringMap.count)")
           print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
            break
        case .update:
            // Will not be hit in this example
            break
        case .error:
            break
        }
    }
    try! realm.write {
        myStringMap["nameOfDog"] = "Rex"
    }
    

    If no key paths are given, the block will be executed on any insertion, modification, or deletion for all object properties and the properties of any nested, linked objects. If a key path or key paths are provided, then the block will be called for changes which occur only on the provided key paths. For example, if:

    class Dog: Object {
        @Persisted var name: String
        @Persisted var age: Int
        @Persisted var toys: List<Toy>
    }
    // ...
    let dogs = myObject.mapOfDogs
    let token = dogs.observe(keyPaths: ["name"]) { changes in
        switch changes {
        case .initial(let dogs):
           // ...
        case .update:
           // This case is hit:
           // - after the token is initialized
           // - when the name property of an object in the
           // collection is modified
           // - when an element is inserted or removed
           //   from the collection.
           // This block is not triggered:
           // - when a value other than name is modified on
           //   one of the elements.
        case .error:
            // ...
        }
    }
    
    • If the observed key path were ["toys.brand"], then any insertion or deletion to the toys list on any of the collection’s elements would trigger the block. Changes to the brand value on any Toy that is linked to a Dog in this collection will trigger the block. Changes to a value other than brand on any Toy that is linked to a Dog in this collection would not trigger the block. Any insertion or removal to the Dog type collection being observed would also trigger a notification.
    • If the above example observed the ["toys"] key path, then any insertion, deletion, or modification to the toys list for any element in the collection would trigger the block. Changes to any value on any Toy that is linked to a Dog in this collection would not trigger the block. Any insertion or removal to the Dog type collection being observed would still trigger a notification.

    Note

    Multiple notification tokens on the same object which filter for separate key paths do not filter exclusively. If one key path change is satisfied for one notification token, then all notification token blocks for that object will execute.

    You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call invalidate() on the token.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only.

    Note

    The keyPaths parameter refers to object properties of the collection type and does not refer to particular key/value pairs within the Map.

    Declaration

    Swift

    public func observe(keyPaths: [String]? = nil,
                        on queue: DispatchQueue? = nil,
                        _ block: @escaping (RealmMapChange<Map>) -> Void)
    -> NotificationToken

    Parameters

    keyPaths

    Only properties contained in the key paths array will trigger the block when they are modified. If nil, notifications will be delivered for any property change on the object. String key paths which do not correspond to a valid a property will throw an exception. See description above for more detail on linked properties.

    queue

    The serial dispatch queue to receive notification on. If nil, notifications are delivered to the current thread.

    block

    The block to be called whenever a change occurs.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

  • Registers a block to be called each time the map changes.

    The block will be asynchronously called on the actor with the initial map, and then called again after each write transaction which changes either which keys are present in the map or the values of any of the objects.

    The change parameter that is passed to the block reports, in the form of keys within the map, which of the key-value pairs were added, removed, or modified during each write transaction.

    Notifications are delivered to a function isolated to the given actor, on that actors executor. If the actor is performing blocking work, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection, and changes are only reported for writes which occur after the initial notification is delivered.

    If no key paths are given, the block will be executed on any insertion, modification, or deletion for all object properties and the properties of any nested, linked objects. If a key path or key paths are provided, then the block will be called for changes which occur only on the provided key paths. For example, if:

    class Dog: Object {
        @Persisted var name: String
        @Persisted var age: Int
        @Persisted var toys: List<Toy>
    }
    // ...
    let dogs = myObject.mapOfDogs
    let token = dogs.observe(keyPaths: ["name"], on: actor) { actor, changes in
        switch changes {
        case .initial(let dogs):
            // ...
        case .update:
            // This case is hit:
            // - after the token is initialized
            // - when the name property of an object in the collection is modified
            // - when an element is inserted or removed from the collection.
            // This block is not triggered:
            // - when a value other than name is modified on one of the elements.
        case .error:
            // No longer possible and left for backwards compatibility
        }
    }
    
    • If the observed key path were ["toys.brand"], then any insertion or deletion to the toys list on any of the collection’s elements would trigger the block. Changes to the brand value on any Toy that is linked to a Dog in this collection will trigger the block. Changes to a value other than brand on any Toy that is linked to a Dog in this collection would not trigger the block. Any insertion or removal to the Dog type collection being observed would also trigger a notification.
    • If the above example observed the ["toys"] key path, then any insertion, deletion, or modification to the toys list for any element in the collection would trigger the block. Changes to any value on any Toy that is linked to a Dog in this collection would not trigger the block. Any insertion or removal to the Dog type collection being observed would still trigger a notification.

    You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call invalidate() on the token.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only.

    Note

    The keyPaths parameter refers to object properties of the collection type and does not refer to particular key/value pairs within the Map.

    Declaration

    Swift

    @available(macOS 10.15, tvOS 13.0, iOS 13.0, watchOS 6.0, *)
    @_unsafeInheritExecutor
    public func observe<A: Actor>(
        keyPaths: [String]? = nil, on actor: A,
        _ block: @Sendable @escaping (isolated A, RealmMapChange<Map>) -> Void
    ) async -> NotificationToken

    Parameters

    keyPaths

    Only properties contained in the key paths array will trigger the block when they are modified. If nil, notifications will be delivered for any property change on the object. String key paths which do not correspond to a valid a property will throw an exception. See description above for more detail on linked properties.

    actor

    The actor which notifications should be delivered on. The block is passed this actor as an isolated parameter, allowing you to access the actor synchronously from within the callback.

    block

    The block to be called whenever a change occurs.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

  • Registers a block to be called each time the map changes.

    The block will be asynchronously called on the actor with the initial map, and then called again after each write transaction which changes either which keys are present in the map or the values of any of the objects.

    The change parameter that is passed to the block reports, in the form of keys within the map, which of the key-value pairs were added, removed, or modified during each write transaction.

    Notifications are delivered to a function isolated to the given actor, on that actors executor. If the actor is performing blocking work, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection, and changes are only reported for writes which occur after the initial notification is delivered.

    The block will be called for changes which occur only on the provided key paths. For example, if:

    class Dog: Object {
        @Persisted var name: String
        @Persisted var age: Int
        @Persisted var toys: List<Toy>
    }
    // ...
    let dogs = myObject.mapOfDogs
    let token = dogs.observe(keyPaths: [\.name], on: actor) { actor, changes in
        switch changes {
        case .initial(let dogs):
            // ...
        case .update:
            // This case is hit:
            // - after the token is initialized
            // - when the name property of an object in the collection is modified
            // - when an element is inserted or removed from the collection.
            // This block is not triggered:
            // - when a value other than name is modified on one of the elements.
        case .error:
            // No longer possible and left for backwards compatibility
        }
    }
    
    • If the observed key path were [\.toys.brand], then any insertion or deletion to the toys list on any of the collection’s elements would trigger the block. Changes to the brand value on any Toy that is linked to a Dog in this collection will trigger the block. Changes to a value other than brand on any Toy that is linked to a Dog in this collection would not trigger the block. Any insertion or removal to the Dog type collection being observed would also trigger a notification.
    • If the above example observed the [\.toys] key path, then any insertion, deletion, or modification to the toys list for any element in the collection would trigger the block. Changes to any value on any Toy that is linked to a Dog in this collection would not trigger the block. Any insertion or removal to the Dog type collection being observed would still trigger a notification.

    You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call invalidate() on the token.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only.

    Note

    The keyPaths parameter refers to object properties of the collection type and does not refer to particular key/value pairs within the Map.

    Declaration

    Swift

    @available(macOS 10.15, tvOS 13.0, iOS 13.0, watchOS 6.0, *)
    @_unsafeInheritExecutor
    public func observe<A: Actor>(
        keyPaths: [PartialKeyPath<Value.Wrapped>], on actor: A,
        _ block: @Sendable @escaping (isolated A, RealmMapChange<Map>) -> Void
    ) async -> NotificationToken where Value: OptionalProtocol, Value.Wrapped: ObjectBase

    Parameters

    keyPaths

    Only properties contained in the key paths array will trigger the block when they are modified. If nil, notifications will be delivered for any property change on the object. String key paths which do not correspond to a valid a property will throw an exception. See description above for more detail on linked properties.

    actor

    The actor which notifications should be delivered on. The block is passed this actor as an isolated parameter, allowing you to access the actor synchronously from within the callback.

    block

    The block to be called whenever a change occurs.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

Frozen Objects

  • Indicates if the Map is frozen.

    Frozen Maps are immutable and can be accessed from any thread. Frozen Maps are created by calling -freeze on a managed live Map. Unmanaged Maps are never frozen.

    Declaration

    Swift

    public var isFrozen: Bool { get }
  • Returns a frozen (immutable) snapshot of a Map.

    The frozen copy is an immutable Map which contains the same data as this Map currently contains, but will not update when writes are made to the containing Realm. Unlike live Maps, frozen Maps can be accessed from any thread.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only.

    Warning

    This method may only be called on a managed Map.

    Warning

    Holding onto a frozen Map for an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. See RLMRealmConfiguration.maximumNumberOfActiveVersions for more information.

    Declaration

    Swift

    public func freeze() -> Map
  • Returns a live version of this frozen Map.

    This method resolves a reference to a live copy of the same frozen Map. If called on a live Map, will return itself.

    Declaration

    Swift

    public func thaw() -> Map?
  • Returns a human-readable description of the objects contained in the Map.

    Declaration

    Swift

    public override var description: String { get }

Map

  • A publisher that emits Void each time the collection changes.

    Despite the name, this actually emits after the collection has changed.

    Declaration

    Swift

    public var objectWillChange: RealmPublishers.WillChange<Map> { get }

Sequence Support

Available where Key: Decodable, Value: Decodable

Available where Key: Encodable, Value: Encodable