Swiftpack.co - dariopellegrini/StorageDone-iOS as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by dariopellegrini.
dariopellegrini/StorageDone-iOS 0.12.9
Swift library to make easy using local document-oriented database in iOS apps.
⭐️ 56
🕓 23 weeks ago
.package(url: "https://github.com/dariopellegrini/StorageDone-iOS.git", from: "0.12.9")


Swift library to make easy use local document-oriented databases in iOS apps.


To install StorageDone add this line to your Podfile

pod 'StorageDone'


StorageDone lets you save Codable models in a local database very easily.

First create a model

struct Teacher: Codable {
    let id: String
    let name: String?
    let surname: String?
    let age: Int?
    let cv: String?

Then create a StorageDoneDatabase object and save an instance of a Codable model in it

let teacher = Teacher(id: "id1", name: "Sarah", surname: "Jones", age: 29, cv: "https://my.cv.com/sarah_jones")
let database = StorageDoneDatabase(name: "teachers")

try? database.insert(element: teacher)

Reading database content will retrieve an array of the decleared model

do {
    let savedTeachers: [Teacher] = try database.get()
} catch let e {

Other methods allow filtering and deletion.

Primary key

A model can implement PrimaryKey protocol, in order to have an attribute set as database primary key

struct Teacher: Codable, PrimaryKey {
    let id: String
    let name: String?
    let surname: String?
    let age: Int?
    let cv: String?
    func primaryKey() -> String {
        return "id"

Primary keys come in combination with insert or update methods

let teachers = [Teacher(id: "id1", name: "Sarah", surname: "Jones", age: 29, cv: "https://my.cv.com/sarah_jones"),
                Teacher(id: "id2", name: "Silvia", surname: "Jackson", age: 29, cv: "https://my.cv.com/silvia_jackson"),
                Teacher(id: "id3", name: "John", surname: "Jacobs", age: 30, cv: "https://my.cv.com/john_jackobs")]

try? database.insertOrUpdate(elements: teachers)


Database objects can use different custom operators, which wrap try-catch logic and give a more compact way to access database

// Insert or update
database ++= teachers

// Read
let teachers: [Teacher] = <-database

// Filter
let filteredTeachers: [Teacher] = ["id":"id1"] <- database

// Delete if model implements PrimaryKey protocol
database --= teachers


Get and delete commands can use queries. Queries can be built in different ways, using custom operator or extensions on parameter name

// Equal
"id" *== "id1"

// Comparison (Numeric only)
"age" *> 20

"age" *>= 20

"age" *< 20

"age" *<= 20

"age" <=&&<= (10, 20)
"age".between((10, 20))

// Is nil

// Is not nil

// Value inside array
"id" |> ["id1", "id2", "id3"]
"id".inside(["id1", "id2", "id3"])

// Array contains value
"array" |< "A1"

// Like
"name" **= "A%"

// Regex
"city" /== "\\bEng.*e\\b"

// Dates comparisons
"dateCreated" *> Date()

"dateCreated" *>= Date()

"dateCreated" *< Date()

"dateCreated" *<= Date()

"dateCreated" <=&&<= (Date().addingTimeInterval(500), Date().addingTimeInterval(1000))

// And
and(expression1, expression2, expression3)

// Or
or(expression1, expression2, expression3)

// Usage
do {
    let teachers: [Teacher] = try database.get(expression)
} catch let e {

Live queries

Using live queries it's possible to observe database changes.

// All elements
let liveQuery = try storage.live(Teacher.self) {
    teachers in
        print("Count \(teachers.count)")
let liveQuery = try storage.live {
    (teachers: [Teacher]) in
        print("Count \(teachers.count)")

// Elements with query
let liveQuery = try storage.live(Teacher.self, expression: "id".equal("id1")) {
    teachers in

let liveQuery = try storage.live("id".equal("id1")) {
    (teachers: [Teacher]) in

In order to stop observing just call cancel on LiveQuery object.


Advanced queries

Using advanced queries lets to specify filtering expression, ordering logic and priority, limit and skip values. All of these parameters are optional. The only limitation is that skip is ignored if limit parameter is not present.

try database.get {
    $0.expression = or("id".equal("id1"), "name".equal("Silvia"), "name".equal("John"))
    $0.orderings = ["name".ascending, "date".descending]
    $0.limit = 3
    $0.skip = 2

let teachers: [Teacher] = {
    $0.expression = or("id".equal("id1"), "name".equal("Silvia"), "name".equal("John"))
    $0.orderings = ["name".ascending, "date".descending]
    $0.limit = 3
    $0.skip = 2
 } <- databaseCore
try database.live({
    $0.expression = or("id".equal("id1"), "name".equal("Silvia"), "name".equal("John"))
    $0.orderings = ["name".ascending, "date".descending]
    $0.limit = 3
    $0.skip = 2
}) {
    (liveTeachers: [Teacher]) in
    print("Count \(liveTeachers.count)")

Query options

Another way to perform queries using DSL is through QueryOption enum.

let teachers: [Teacher] = try storage.get(
    .expression(or("name".equal("Silvia"), "name".equal("Sara"))),

Fulltext search

Fulltext search needs to be configured with the parameters' name that should be indexed. After that, a query can be performed with search text and with an optional advanced query.

// Define the index
try database.fulltextIndex(Teacher.self, values: "id", "name", "surname", "age", "cv")

// All results
let teachers: [Teacher] = try self.database.search(text: text)

// Results with advanced query
let teachers: [Teacher] = try self.database.search(text: text) {
    $0.orderings = ["age".descending]


Every operation has its RxSwift version. Each can be used through rx extension







RxSwift live queries

Live queries are also available through RxSwift extensions.

// All elements
let disposable = database.rx.live(Teacher.self).subscribe(onNext: {
    teachers in
    print("Count \(teachers.count)")

let disposable = database.rx.live().subscribe(onNext: {
    (teachers: [Teacher]) in
    print("Count \(teachers.count)")

// Elements with query
let disposable = database.rx.live(Teacher.self, expression: "id".equal("id1")).subscribe(onNext: {
    teachers in
    print("Count \(teachers.count)")

let disposable = database.rx.live("id".equal("id1")).subscribe(onNext: {
    (teachers: [Teacher]) in
    print("Count \(teachers.count)")

To stop observing changes just dispose the disposable or alternatively add it to a dispose bag.


// or

disposable.disposed(by: disposeBag)

Async await

Every operation has its async await version. By default they are on a .medium priority task.

let teachers: [Teacher] = try await database.async.insertOrUpdate(teachers)

let teachers: [Teacher] = try await database.async.insert(teachers)

let teachers: [Teacher] = try await database.async.get()

let teachers: [Teacher] = try await database.async.get {
    $0.expression = "id".equal(id)

let teachers: [Teacher] = try await database.async.get(.expression("id".equal("id1")))

let teachers: [Teacher] = try await database.async.delete(["id":"id2"])

let teachers: [Teacher] = try await database.async.deleteAllAndInsert(teachers)

To run every task with a different priority simply specify it in the async extension.

let teachers: [Teacher] = try await database.async(.userInitiated).get()

Async streams

Live queries can be represented using Swift async streams.

task = Task {
    for try await teachers: [Teacher] in database.async.live() {
        print("Count \(teachers.count)")

To stop observing changes just cancel the task.



StorageDone has the function publisher which let to observe any change as well as live queries.

database.publisher(Teacher.self).sink { ... }

database.publisher(Teacher.self, "id".equal(id)).sink { ... }

database.publisher(Teacher.self) {
            $0.expression = "id".equal(id)
            $0.orderings = ["name".ascending]
            $0.limit = 10
        }.sink { ... }


Taking as inspiration the @AppStorage property wrapper, StorageDone integrates its property wrapper to make it easy to save and observe database persistent data.

Add the AppStorageDone property wrapper, giving as input the name of the database. Other constructors are available for this. This will create an array of the specified type that will persist in the database.

@AppStorageDone(databaseName: "saiyans") var saiyans: [Saiyan]

After that, any update of saiyans will persist on the database and update every view bound to it.

saiyans.append(Saiyan(name: "Goku"))

saiyans.remove(at: 0)


Add AppStorageDoneValue property wrapper, giving as input the name of the database and an id. It is very similar to AppStorage property wrapper. This will create an object that will be saved on the database. The initial value is a default. This means that is ignored if another one is present in the database.

@AppStorageDoneValue(databaseName: "saiyans", id: "planet") var planet = Planet(name: "Earth")

Any update will persist on the database and update any view bound to it.

planet.name = "Namek"

StorageDoneVariable (beta)

StorageDone brings StorageDoneVariable, a struct that tries to emulate BehaviorSubject features, using the local database as a data container. First create a StorageDoneVariable.

let variable: StorageDoneVariable<Teacher> = database.variable()

This object is an abstraction layer that allows one to perform read, write and observe operations on the database.

Read and write

Read and write can be performed synchronously or asynchronously.

// Synchronously
let teachers = variable.elements
variable.accept(elements: teachers)

// Asynchronously
let teachers = await variable.asyncElements
variable.acceptAsync(elements: teachers)

By default accept performs an insertOrUpdate operation, replacing the already existing elements and adding the new ones. Adding the parameter delete to accept functions makes variable perform a deleteAllAndInsert operation, replacing all the elements of the collection with new ones.

Observing data

To observe data with StorageDoneVariable there are 2 possible ways.

// Rx
variable.observable.subscribe(onNext: { teachers in })

// AsyncStream
for try await teacher in variables.asyncStream {


Dario Pellegrini, [email protected]


CouchbaseLite iOS


Antonio Petruccelli


StorageDone-iOS is available under the MIT license. See the LICENSE file for more info.

Donate with PayPal


Stars: 56
Last commit: 3 weeks ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics