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 exceptObject
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, Map
s 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>
.
-
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 }
-
Creates a
Map
that holds Realm model objects of typeValue
.Declaration
Swift
public override init()
-
Returns the number of key-value pairs in this map.
Declaration
Swift
@objc public var count: Int { get }
-
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.
-
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.
-
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
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.
-
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
Date
s from newest to oldest based, you might calldates.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
Student
s from youngest to oldest based on theirage
property, you might callstudents.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
-
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.
-
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 thetoys
list on any of the collection’s elements would trigger the block. Changes to thebrand
value on anyToy
that is linked to aDog
in this collection will trigger the block. Changes to a value other thanbrand
on anyToy
that is linked to aDog
in this collection would not trigger the block. Any insertion or removal to theDog
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 thetoys
list for any element in the collection would trigger the block. Changes to any value on anyToy
that is linked to aDog
in this collection would not trigger the block. Any insertion or removal to theDog
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.
- If the observed key path were
-
observe(keyPaths:
Asynchronouson: _: ) 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 thetoys
list on any of the collection’s elements would trigger the block. Changes to thebrand
value on anyToy
that is linked to aDog
in this collection will trigger the block. Changes to a value other thanbrand
on anyToy
that is linked to aDog
in this collection would not trigger the block. Any insertion or removal to theDog
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 thetoys
list for any element in the collection would trigger the block. Changes to any value on anyToy
that is linked to aDog
in this collection would not trigger the block. Any insertion or removal to theDog
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.
- If the observed key path were
-
observe(keyPaths:
Asynchronouson: _: ) 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 thetoys
list on any of the collection’s elements would trigger the block. Changes to thebrand
value on anyToy
that is linked to aDog
in this collection will trigger the block. Changes to a value other thanbrand
on anyToy
that is linked to aDog
in this collection would not trigger the block. Any insertion or removal to theDog
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 thetoys
list for any element in the collection would trigger the block. Changes to any value on anyToy
that is linked to aDog
in this collection would not trigger the block. Any insertion or removal to theDog
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.
- If the observed key path were
-
Indicates if the
Map
is frozen.Frozen
Map
s are immutable and can be accessed from any thread. FrozenMap
s are created by calling-freeze
on a managed liveMap
. UnmanagedMap
s 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 thisMap
currently contains, but will not update when writes are made to the containing Realm. Unlike liveMap
s, frozenMap
s 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 managedMap
.Warning
Holding onto a frozenMap
for an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. SeeRLMRealmConfiguration.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 liveMap
, 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 }
-
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 }
-
Returns a
RLMMapIterator
that yields successive elements in theMap
.Declaration
Swift
public func makeIterator() -> RLMMapIterator<SingleMapEntry<Key, Value>>
-
An adaptor for Map which makes it a sequence of
See more(key: Key, value: Value)
instead of a sequence ofSingleMapEntry
.Declaration
Swift
public struct KeyValueSequence : Sequence
-
Returns this Map as a sequence of
(key: Key, value: Value)
Declaration
Swift
public func asKeyValueSequence() -> KeyValueSequence
-
Declaration
Swift
public convenience init(from decoder: Decoder) throws
-
Declaration
Swift
public func encode(to encoder: Encoder) throws