Quick Start - Swift SDK
On this page
Prerequisites
Before you begin, ensure you have Installed the Swift SDK.
For a quickstart featuring communicating with a backend Realm app over the network using Sync, Realm Functions, or user management, see the Quick Start with Sync, or the full iOS Tutorial.
Import Realm
Near the top of any Swift file that uses Realm, add the following import statement:
import RealmSwift
Define Your Object Model
For a local-only Realm Database you can define your object model directly in code.
// LocalOnlyQsTask is the Task model for this QuickStart class LocalOnlyQsTask: Object { var name: String = "" var owner: String? var status: String = "" convenience init(name: String) { self.init() self.name = name } }
Open a Realm
In a local-only Realm Database, the simplest option to open a realm is by omitting the configuration parameter, which uses the default realm:
// Open the local-only default realm let localRealm = try! Realm()
You can also specify a Realm.Configuration parameter to open a realm at a specific file URL, in-memory, or with a subset of classes.
Create, Read, Update, and Delete Objects
Once you have opened a realm, you can modify it and its objects in a write transaction block.
To create a new Task, instantiate the Task class and add it to the realm in a write block:
// Add some tasks let task = LocalOnlyQsTask(name: "Do laundry") try! localRealm.write { localRealm.add(task) }
You can retrieve a live collection of all tasks in the realm:
// Get all tasks in the realm let tasks = localRealm.objects(LocalOnlyQsTask.self)
You can also query that collection using where:
// You can also filter a collection let tasksThatBeginWithA = tasks.where { $0.name.starts(with: "A") } print("A list of all tasks that begin with A: \(tasksThatBeginWithA)")
To modify a task, update its properties in a write transaction block:
// All modifications to a realm must happen in a write block. let taskToUpdate = tasks[0] try! localRealm.write { taskToUpdate.status = "InProgress" }
Finally, you can delete a task:
// All modifications to a realm must happen in a write block. let taskToDelete = tasks[0] try! localRealm.write { // Delete the LocalOnlyQsTask. localRealm.delete(taskToDelete) }
Watch for Changes
You can watch a realm, collection, or object for changes with the observe
method.
Be sure to retain the notification token returned by observe
as
long as you want to continue observing. When you are done observing,
invalidate the token to free the resources.
// Retain notificationToken as long as you want to observe let notificationToken = tasks.observe { (changes) in switch changes { case .initial: break // Results are now populated and can be accessed without blocking the UI case .update(_, let deletions, let insertions, let modifications): // Query results have changed. print("Deleted indices: ", deletions) print("Inserted indices: ", insertions) print("Modified modifications: ", modifications) case .error(let error): // An error occurred while opening the Realm file on the background worker thread fatalError("\(error)") } }
Later, when done observing:
// Invalidate notification tokens when done observing notificationToken.invalidate()
Complete Example
Run the complete example by calling runLocalOnlyExample()
.
import RealmSwift // LocalOnlyQsTask is the Task model for this QuickStart class LocalOnlyQsTask: Object { var name: String = "" var owner: String? var status: String = "" convenience init(name: String) { self.init() self.name = name } } // Entrypoint. Call this to run the example. func runLocalOnlyExample() { // Open the local-only default realm let localRealm = try! Realm() // Get all tasks in the realm let tasks = localRealm.objects(LocalOnlyQsTask.self) // Retain notificationToken as long as you want to observe let notificationToken = tasks.observe { (changes) in switch changes { case .initial: break // Results are now populated and can be accessed without blocking the UI case .update(_, let deletions, let insertions, let modifications): // Query results have changed. print("Deleted indices: ", deletions) print("Inserted indices: ", insertions) print("Modified modifications: ", modifications) case .error(let error): // An error occurred while opening the Realm file on the background worker thread fatalError("\(error)") } } // Delete all from the realm try! localRealm.write { localRealm.deleteAll() } // Add some tasks let task = LocalOnlyQsTask(name: "Do laundry") try! localRealm.write { localRealm.add(task) } let anotherTask = LocalOnlyQsTask(name: "App design") try! localRealm.write { localRealm.add(anotherTask) } // You can also filter a collection let tasksThatBeginWithA = tasks.where { $0.name.starts(with: "A") } print("A list of all tasks that begin with A: \(tasksThatBeginWithA)") // All modifications to a realm must happen in a write block. let taskToUpdate = tasks[0] try! localRealm.write { taskToUpdate.status = "InProgress" } let tasksInProgress = tasks.where { $0.status == "InProgress" } print("A list of all tasks in progress: \(tasksInProgress)") // All modifications to a realm must happen in a write block. let taskToDelete = tasks[0] try! localRealm.write { // Delete the LocalOnlyQsTask. localRealm.delete(taskToDelete) } print("A list of all tasks after deleting one: \(tasks)") // Invalidate notification tokens when done observing notificationToken.invalidate() }