Navigation

Map (beta) - iOS SDK

On this page

  • Overview
  • Usage

New in version 10.8.0: Map

Warning

This feature is currently in beta. We encourage you to try out the feature and give feedback, but please be aware that:

  • The API may change.
  • New data types are not backwards compatible.

To add new data types via development mode, you must update the client SDK. Realm Sync client applications using older protocol versions will no longer be able to connect.

The Map is an associative array that contains key-value pairs with unique keys.

Like Swift's Dictionary, Map is a generic type that is parameterized on its key and value types. Unlike native Swift collections, Realm Maps are reference types (classes), as opposed to value types (structs).

You can declare a Map as a property of an object:

class Dog: Object {
@Persisted var name = ""
@Persisted var currentCity = ""
// Map of city name -> favorite park in that city
@Persisted var favoriteParksByCity: Map<String, String>
}
Note

When declaring default values for @Persisted Map property attributes, both of these syntax types is valid:

  • @Persisted var value: Map<String, String>
  • @Persisted var value = Map<String, String>()

However, the second will result in significantly worse performance. This is because the Map is created when the parent object is created, rather than lazily as needed.

You can then update, check values, iterate over, and delete from the Map as you would a standard Dictionary:

let realm = try! Realm()
// Record a dog's name and current city
let dog = Dog()
dog.name = "Wolfie"
dog.currentCity = "New York"
// Store the data in a realm
try! realm.write {
realm.add(dog)
// Set values
dog.favoriteParksByCity["New York"] = "Domino Park"
dog.favoriteParksByCity["Chicago"] = "Wiggly Field"
// Another way to set values
dog.favoriteParksByCity.setValue("Bush Park", forKey: "Ottawa")
// Overwrite a value
dog.favoriteParksByCity["New York"] = "Washington Square Park"
}
// Check if an entry exists
if dog.favoriteParksByCity.keys.contains("Chicago") {
print("\(dog.name)' has a favorite park in Chicago")
}
// Iterate over entries
for element in dog.favoriteParksByCity {
print("\(dog.name)'s favorite park in \(element.key) is \(element.value)")
}
// Delete an entry
try! realm.write {
// Use removeObject(for:)
dog.favoriteParksByCity.removeObject(for: "New York")
// Or assign `nil` to delete non-optional values.
// If the value type were optional (e.g. Map<String, String?>)
// this would assign `nil` to that entry rather than deleting it.
dog.favoriteParksByCity["New York"] = nil
}
Give Feedback

On this page

  • Overview
  • Usage