TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Oct 2017 |
SwiftSwift Version | 4.0 |
SPMSupports SPM | ✗ |
Maintained by Christopher Szatmary.
QuickPersist provides an easy way to save Swift structs to a Realm database.
In order to persist a struct to a Realm, the struct must conform to the Persistable
protocol.
Persistable
requires conforming types to conform to Codable
.
Persistable
requires two properties to be implemented.
typeName
: a String
that represents the name of the struct.primaryKey
: a String
value that is a unique identifier for the instancestruct Person {
var name: String
var age: Int
let id: String
}
extension Person: Persistable {
static var typeName: String {
return "Person"
}
var primaryKey: String {
return id
}
}
That's it! QuickPersist takes care of the rest. This struct is now ready to be persisted.
QuickPersist provides a type called RealmOperator that lets you do basic operations on a Realm that involve Persistable types.
let op = try! RealmOperator() // Creates a new RealmOperator from the default Realm.
Or
let op = RealmOperator(realm: myCustomRealm) // Creates a new RealmOperator from the given Realm.
WriteTransaction provides an interface for interacting with a Realm during a write transaction. It should only every be used inside a RealmOperator write block.
Here's an example of how to save a struct to a Realm:
let person = Person(name: "John Doe", age: 20, id: UUID().uuidString)
let op = try! RealmOperator()
try! op.write { (writeTransaction) in
try! writeTransaction.add(person, update: true)
}
WriteTransaction takes Persistable instances directly, and performs the necessary actions to save it to the Realm. No extra work required.
QPResults is a special wrapper over Realm's Results
that provides an easy way to get persisted values back in their original form.
Here's an example of getting values from a Realm:
let op = try! RealmOperator()
let results = op.values(ofType: Person.self)
let person = results[0] // Returns an instance of Person.
Or if you can get a specific value with an id:
let person = op.value(ofType: Person.self, withPrimaryKey: id)
Open an issue or submit a pull request.