What is Realm and why is it needed?
Realm is a mobile database created as an alternative to Core Data and SQLite. Unlike traditional relational databases, Realm works as an object-oriented storage: you work with native Swift objects, not SQL queries or NSManagedObject. Realm stores data in its own format, providing performance close to working with RAM.
Main advantages of Realm:
- Speed: Realm works 10-100 times faster than SQLite on mobile devices.
- Simplicity: You work with regular Swift objects by inheriting them from Realm.Object.
- Automatic updates: Query results (Results) automatically update when data changes.
- Live objects: Realm objects automatically synchronize with the database.
- Cross-platform: Realm works on iOS, macOS, tvOS, and watchOS.
Realm is ideal for applications that require fast access to data on the device: todo lists, messengers, caching data from the network, note-taking apps, and many others.
Installing Realm in Swift
Realm for Swift is installed via Swift Package Manager (SPM), CocoaPods, or Carthage. Let's look at the two most popular methods.
Installation via Swift Package Manager (recommended)
- In Xcode, open your project:
File → Add Packages... - Paste the URL:
https://github.com/realm/realm-swift.git - Select the version (latest stable is recommended) and click
Add Package. - In the window that appears, select the
RealmandRealmSwiftpackages for your target build.
Installation via CocoaPods
Add to your Podfile:
target 'YourApp' do use_frameworks! pod 'RealmSwift'endThen run in the terminal:
pod installImport in code
import RealmSwiftQuick start: first model and data writing
Let's create a simple task model and save it to the database.
import RealmSwift
// 1. Define the modelclass Task: Object { @Persisted var id: String = UUID().uuidString @Persisted var title: String = "" @Persisted var isCompleted: Bool = false @Persisted var createdAt: Date = Date() // Primary key (optional but recommended) override static func primaryKey() -> String? { return "id" }}
// 2. Save the objectlet task = Task()task.title = "Buy groceries"task.isCompleted = false
let realm = try! Realm()try! realm.write { realm.add(task)}
// 3. Read all taskslet tasks = realm.objects(Task.self)for task in tasks { print("\\(task.title) - \\(task.isCompleted ? "Completed" : "Not completed")")}Main Realm methods and functions
Below are the key methods for working with Realm. Each method is accompanied by a description, parameters, and a working example.
1. Realm() — Database initialization
What it does: Creates or opens an existing Realm database. By default, the database file is located in the app's Documents directory.
Parameters: configuration: Realm.Configuration? — optional configuration (file URL, schema, migration version).
// Standard initializationlet realm = try! Realm()
// Initialization with custom URLlet config = Realm.Configuration(fileURL: FileManager.default .urls(for: .documentDirectory, in: .userDomainMask) .first?.appendingPathComponent("myrealm.realm"))let customRealm = try! Realm(configuration: config)