Docs Menu

Map - Swift SDK

On this page

  • Overview
  • Usage

New in version 10.8.0.

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>

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() = "Wolfie"
dog.currentCity = "New York"
// Store the data in a realm
try! realm.write {
// 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("\(' has a favorite park in Chicago")
// Iterate over entries
for element in dog.favoriteParksByCity {
print("\('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
←  Collections - Swift SDKMutableSet - Swift SDK →

On this page

Give Feedback
© 2022 MongoDB, Inc.


  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.