Swiftpack.co - Package - EcolabCompany/RealmExtensions


This package provides handy extensions For Realm


chainWrite is a replacement for Realm's write function

public func chainWrite(_ f: () throws -> ()) {
    if self.isInWriteTransaction {
        try! f()
    } else {
        try! self.write {
            try! f()

This allows you to safely call write transactions when you may already be in a write transaction and not know it


RealmTransaction is a struct with a property transaction: (Realm) -> (). This property represents a future Realm database write. RealmTransaction allow you to build complex Realm database writes by composing smaller transactions together.

To create a RealmTransaction, you can simply call one of the two initializers

let saveTransaction = RealmTransaction { realm in 
    realm.write {


let deleteTransaction = RealmTranscation { 
    try! Realm().delete(anotherObject)

Then, to commit the transaction to the Realm database, you call


Chaining multiple transactions

Often, multiple / complex transactions need to be committed to the database. RealmTransaction provides a custom operator to chain multiple transactions together

public func <-> (lhs: RealmTransaction, rhs: RealmTransaction) -> RealmTransaction {
    RealmTransaction.init(transaction: lhs.transaction <> rhs.transaction)


let transaction = saveTransaction <-> deleteTransaction

Convenience Operators

RealmTransaction comes with many convenience operators

public static func add(_ object: Object) -> RealmTransaction
public static func add(_ object: Object?) -> RealmTransaction
public static func add(_ objects: [Object]) -> RealmTransaction
public static func delete(_ object: Object) -> RealmTransaction
public static func delete<S>(_ objects: S) -> RealmTransaction where S: Sequence, S.Element: Object

refresh() -> RealmTransaction calls realm.refresh before the transaction is comitted

public func reduce() -> RealmTransaction reduces an array of RealmTranscactions down to a single RealmTransaction

public func set<Value>(_ keyPath: ReferenceWritableKeyPath<Self, Value>, _ value: Value) -> RealmTransaction allows you to set an Object's property through keyPaths

let transaction = object.set(\.name, "luke")


Stars: 0


Used By

Total: 0