-
Notifications
You must be signed in to change notification settings - Fork 60
Dealing with optional variables (basic types and enum) #81
Copy link
Copy link
Open
Description
I am learning how to use Genome, and so far I am impressed with the flexibility offered by Genome. 👍
- Is it possible to declare optional variables (both basic type and enum) that will not be mapped to JSON at all if they are nil?
- An extension to this question is how do I specify the transformToNode and transformFromNode functions for these optional variables?
- I am trying to extend Date class, making it NodeRepresentable and NodeConvertible. (See code below). Would this implementation be able to handle when date is nil during serialization (my intention is to skip saving date data if date is nil) and when the JSON data is absent during deserialization (my intention is to leave the date variable uninitialized)?
extension Date: NodeRepresentable {
public func makeNode(context: Context = EmptyNode) throws -> Node {
return .string(self.ISO8601String())
}
}
extension Date: NodeConvertible {
public init(node: Node, in context: Context) throws {
guard let string = node.string else {
throw NodeError.unableToConvert(node: node, expected: "\(String.self)")
}
guard let date = Date.dateFromISO8601String(string: string) else {
throw NodeError.unableToConvert(node: node, expected: "Date is stored in ISO8601 format")
}
self = date
}
}Example class definition:
enum FooType: Int8 {
case typeA
case typeB
}
class Bar: BasicMappable {
var foo: FooType?
var date: Date?
var name: String?
required init() {
}
func sequence(map: Map) throws {
try foo <~> map["foo"]
try date <~> map["date"]
try name <~> map["name"]
}
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels