Docs Menu

Realm Swift SDK

On this page

  • Realm Database
  • Define an Object Schema
  • Create an Object
  • Query Realm Database
  • Update Live Objects
  • Watch for Updates
  • Always Access the Latest Data
  • Atlas App Services Apps
  • Atlas Device Sync
  • App Services
  • OS Support (Xcode 13)
  • OS Support (Xcode 14)
  • Async/Await Support

The Realm Database Swift SDK enables mobile applications to access data stored in local realms. Optionally, interact with App Services features such as Functions, MongoDB Data Access, and authentication. The Realm Swift SDK supports Swift and Objective-C, and provides SwiftUI-friendly property wrappers.

Tip
See also:

Are you looking for information about using Swift with MongoDB in a backend app, command-line utility, or running on macOS or Linux? See the MongoDB Swift Driver documentation.

With the Realm Swift SDK, you can access objects stored in a local instance of Realm Database.

Use Swift to idiomatically define an object schema.

class CoffeeDrink: Object {
@Persisted var name = ""
@Persisted var hotOrCold: String?
@Persisted var rating = 0
}

Create a new object as you would instantiate any other object. Then, pass it to Realm Database inside a write transaction.

let realm = try! Realm()
try! realm.write {
// Add coffee shop and drink info here.
let shop = CoffeeShop()
shop.name = "Better Coffee"
let drink = CoffeeDrink()
drink.name = "Maple Latte"
drink.rating = 7
shop.drinks.append(drink)
realm.add(shop)
}

Query for stored objects using Swift-idiomatic queries.

let realm = try! Realm()
let drinks = realm.objects(CoffeeDrink.self)
let highlyRatedDrinks = drinks.where {
$0.rating > 6
}
print("Highly-rated drinks: \(highlyRatedDrinks.count)")
let mapleOrCaramelLattes = drinks.where {
$0.name == "Maple Latte" || $0.name == "Caramel Latte"
}
print("Number of maple or caramel lattes: \(mapleOrCaramelLattes.count)")
let drinkTempNotSpecified = drinks.where {
$0.hotOrCold == nil
}
print("No info about drink temp: \(drinkTempNotSpecified.count)")

Update objects by updating field values on an instance of the object within a transaction.

let realm = try! Realm()
// Get a maple latte
let mapleLatte = realm.objects(CoffeeDrink.self).where {
$0.name == "Maple Latte"
}.first!
// Open a thread-safe transaction
try! realm.write {
// Change the name of the maple latte.
mapleLatte.name = "Maple Delight"
// Specify that the maple latte is a hot drink.
mapleLatte.hotOrCold = "Hot"
} // When the transaction completes, the drink details are updated in the database.

Register a notification handler on an entire realm, a collection, or an object, and react to changes.

var drinkNotificationToken: NotificationToken?
func objectNotificationExample() {
// Create a new drink
let drink = CoffeeDrink()
drink.name = "Spicy Icy Coffee"
drink.rating = 9
// Open the default realm.
let realm = try! Realm()
try! realm.write {
// Add the drink to the realm
realm.add(drink)
}
// Observe changes.
drinkNotificationToken = drink.observe { change in
switch change {
case .change(let object, let properties):
for property in properties {
print("Property '\(property.name)' of object \(object) changed to '\(property.newValue!)'")
}
case .error(let error):
print("An error occurred: \(error)")
case .deleted:
print("The object was deleted.")
}
}
// Now, when you update the object, this triggers the notification
try! realm.write {
drink.name = "Ancho Chili Chocolate Iced Coffee"
}
}

Because Realm Database objects are live objects, they're automatically updated when they're modified.

// Open the default realm.
let realm = try! Realm()
// Create a couple of references to a single underlying coffee drink object
let drinkA = realm.objects(CoffeeDrink.self).where {
$0.name == "Maple Latte"
}.first!
let drinkB = realm.objects(CoffeeDrink.self).where {
$0.name == "Maple Latte"
}.first!
// Update drink A's name
try! realm.write {
drinkA.name = "Maple-iest Latte in Town"
}
// See that drink B instance updates with the new name
XCTAssert(drinkA.name == drinkB.name)
// Update drink B's rating
try! realm.write {
drinkB.rating = 4
}
// See that drink A instance updates with the new rating
XCTAssert(drinkB.rating == drinkA.rating)

Atlas App Services Apps, which we may refer to as Apps, are backends for client applications hosted by MongoDB in the cloud. They provide the ability to synchronize data stored in Realm Database, called Device Sync, as well as a layer of backend functionality collectively called App Services. In addition to working with local Realm Database, the Swift SDK also enables you to leverage the features of Apps.

Create an Account

Use Device Sync to automatically sync your realms across client devices and a Atlas data store backend.

Important

Device Sync does not currently support watchOS.

When you create an App, you get access to a variety of services to streamline app development:

  • User management: built-in user management to enable account creation and authentication
  • Functions: define and execute server-side logic
  • Triggers: react to events or define a schedule to execute automated processes
Supported OS
Realm Database
Realm Apps
iOS 9.0+ (iOS 11+ if using Swift Package Manager)
X
X
macOS 10.9+ (macOS 10.10+ if using Swift Package Manager)
X
X
tvOS 9.0+
X
X
watchOS 2.0+
X
Supported OS
Realm Database
Realm Apps
iOS 11.0+
X
X
macOS 10.13+
X
X
tvOS 11.0+
X
X
watchOS 4.0+
X
Important

There are special considerations when using Realm Database with tvOS. See Build for tvOS for more information.

Starting with Realm Swift SDK Versions 10.15.0 and 10.16.0, many of the Realm APIs support the Swift async/await syntax. Projects must meet these requirements:

Swift SDK Version
Swift Version Requirement
Supported OS
10.25.0
Swift 5.6
iOS 13.x
10.15.0 or 10.16.0
Swift 5.5
iOS 15.x
←  Upgrade from Stitch to Realm - React Native SDKRealm Database - Swift SDK →
Give Feedback
© 2022 MongoDB, Inc.

About

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