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: _RealmSchemaDiscoverable, SchemaDiscoverable where Value: _RealmSchemaDiscoverable
extension Map: _HasPersistedType, _Persistable, _DefaultConstructible where Value: _Persistable
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.
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 of Map type defined on Object subclasses must be declared as let and cannot be dynamic.
-
The Realm which manages the map, or
nilif 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
Mapthat 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
valuea value’s key path predicate.
forKeyThe direction to sort in.
-
Merges the given dictionary into this map, using a combining closure to determine the value for any duplicate keys.
If
dictionarycontains a key which is already present in this map,combinewill 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
dictionaryThe dictionary to merge into this map.
combineA 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
othercontains a key which is already present in this map,combinewill 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) rethrowsParameters
otherThe map to merge into this map.
combineA 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
nilthen 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
keyThe key.
-
Returns a type of
AnyObjectfor a specified key if it exists in the map.Declaration
Swift
@objc public func object(forKey key: AnyObject) -> AnyObject?Parameters
keyThe key to the property whose values are desired.
-
Returns a type of
Valuefor 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
keyThe key to the property whose values are desired.
-
Returns a type of
Valuefor a specified key if it exists in the map.Declaration
Swift
@nonobjc public func value(forKeyPath keyPath: String) -> AnyObject?Parameters
keyPathThe 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
valueThe object value.
keyThe name of the property whose value should be set on each object.
-
Returns a
Resultscontaining 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
predicateThe predicate with which to filter the values.
-
Returns a
Resultscontaining all matching values in the map with the given query.Note
This should only be used with classes using the
@Persistableproperty declaration.Usage:
myMap.where { ($0.fooCol > 5) && ($0.barCol == "foobar") }
Note
See
Queryfor more information on what query operations are available.Declaration
Parameters
isIncludedThe 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) -> BoolParameters
wherea closure that test if any key-pair of the given map represents the match.
-
Returns a
Resultscontaining 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 calldates.sorted(ascending: true).Declaration
Swift
public func sorted(ascending: Bool = true) -> Results<Value>Parameters
ascendingThe direction to sort in.
-
Returns a
Resultscontaining 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 theirageproperty, 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
keyPathThe key path to sort by.
ascendingThe direction to sort in.
-
Returns a
Resultscontaining 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
nilif the map is empty.Warning
Only a property whose type conforms to the
MinMaxTypeprotocol can be specified.Declaration
Swift
public func min<T>(ofProperty property: String) -> T? where T : _HasPersistedType, T.PersistedType : MinMaxTypeParameters
propertyThe 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
nilif the map is empty.Warning
Only a property whose type conforms to the
MinMaxTypeprotocol can be specified.Declaration
Swift
public func max<T>(ofProperty property: String) -> T? where T : _HasPersistedType, T.PersistedType : MinMaxTypeParameters
propertyThe name of a property whose minimum value is desired.
-
Returns the sum of the given property for objects in the collection, or
nilif the map is empty.Warning
Only names of properties of a type conforming to the
AddableTypeprotocol can be used.Declaration
Swift
public func sum<T>(ofProperty property: String) -> T where T : _HasPersistedType, T.PersistedType : AddableTypeParameters
propertyThe name of a property conforming to
AddableTypeto calculate sum on. -
Returns the average value of a given property over all the objects in the collection, or
nilif the map is empty.Warning
Only a property whose type conforms to the
AddableTypeprotocol can be specified.Declaration
Swift
public func average<T>(ofProperty property: String) -> T? where T : _HasPersistedType, T.PersistedType : AddableTypeParameters
propertyThe 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
changeparameter 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.At the time when the block is called, the map will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call
realm.refresh(), accessing it will never perform blocking work.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" } // end of run loop execution contextYou 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.Declaration
Swift
public func observe(on queue: DispatchQueue?, _ block: @escaping (RealmMapChange<Map>) -> Void) -> NotificationTokenParameters
queueThe serial dispatch queue to receive notification on. If
nil, notifications are delivered to the current thread.blockThe 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 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
changeparameter 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.At the time when the block is called, the map will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call
realm.refresh(), accessing it will never perform blocking work.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" } // end of run loop execution contextIf 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: // ... } } // end of run loop execution context- If the observed key path were
["toys.brand"], then any insertion or deletion to thetoyslist on any of the collection’s elements would trigger the block. Changes to thebrandvalue on anyToythat is linked to aDogin this collection will trigger the block. Changes to a value other thanbrandon anyToythat is linked to aDogin this collection would not trigger the block. Any insertion or removal to theDogtype collection being observed would also trigger a notification. If the above example observed the
["toys"]key path, then any insertion, deletion, or modification to thetoyslist for any element in the collection would trigger the block. Changes to any value on anyToythat is linked to aDogin this collection would not trigger the block. Any insertion or removal to theDogtype 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) -> NotificationTokenParameters
keyPathsOnly 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.queueThe serial dispatch queue to receive notification on. If
nil, notifications are delivered to the current thread.blockThe 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
Mapis frozen.Frozen
Maps are immutable and can be accessed from any thread. FrozenMaps are created by calling-freezeon a managed liveMap. UnmanagedMaps are never frozen.Declaration
Swift
public var isFrozen: Bool { get } -
Returns a frozen (immutable) snapshot of a
Map.The frozen copy is an immutable
Mapwhich contains the same data as thisMapcurrently contains, but will not update when writes are made to the containing Realm. Unlike liveMaps, frozenMaps 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 frozenMapfor an extended period while performing write transaction on the Realm may result in the Realm file growing to large sizes. SeeRLMRealmConfiguration.maximumNumberOfActiveVersionsfor 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 }
-
Undocumented
Declaration
Swift
public var _rlmObjcValue: Any { get } -
Undocumented
Declaration
Swift
public static func _rlmFromObjc(_ value: Any) -> `Self`?
-
Returns a
RLMMapIteratorthat 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<Key, Value> : Sequence where Key : _MapKey, Value : RealmCollectionValue -
Returns this Map as a sequence of
(key: Key, value: Value)Declaration
Swift
public func asKeyValueSequence() -> KeyValueSequence<Key, Value>
-
Undocumented
Declaration
Swift
public static var _rlmType: PropertyType { get } -
Undocumented
Declaration
Swift
public static var _rlmOptional: Bool { get } -
Undocumented
Declaration
Swift
public static var _rlmRequireObjc: Bool { get } -
Undocumented
Declaration
Swift
public static func _rlmPopulateProperty(_ prop: RLMProperty)
-
Undocumented
Declaration
Swift
public typealias PersistedType = Map -
Undocumented
Declaration
Swift
public static var _rlmRequiresCaching: Bool { get } -
Undocumented
Declaration
Swift
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: UInt16) -> Self -
Undocumented
Declaration
Swift
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: UInt16, _ value: Map) -
Undocumented
Declaration
Swift
public static func _rlmSetAccessor(_ prop: RLMProperty)
-
Declaration
Swift
public convenience init(from decoder: Decoder) throws
-
Declaration
Swift
public func encode(to encoder: Encoder) throws
View on GitHub
Install in Dash