Skip to content

Instantly share code, notes, and snippets.

@emarashliev
Last active July 5, 2019 08:31
Show Gist options
  • Save emarashliev/72d354f1393e0a89d12eba87994db2f9 to your computer and use it in GitHub Desktop.
Save emarashliev/72d354f1393e0a89d12eba87994db2f9 to your computer and use it in GitHub Desktop.
@propertyWrapper
public struct Field<Value: DatabaseValue> {
public let name: String
private var record: DatabaseRecord?
private var cachedValue: Value?
public init(name: String) {
self.name = name
}
public func configure(record: DatabaseRecord) {
self.record = record
}
public var wrappedValue: Value {
mutating get {
if cachedValue == nil { fetch() }
return cachedValue!
}
set {
cachedValue = newValue
}
}
public func flush() {
if let value = cachedValue {
record!.flush(fieldName: name, value)
}
}
public mutating func fetch() {
cachedValue = record!.fetch(fieldName: name, type: Value.self)
}
}
public struct Person: DatabaseModel {
@Field(name: "first_name") public var firstName: String
@Field(name: "last_name") public var lastName: String
@Field(name: "date_of_birth") public var birthdate: Date
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment