Skip to content

Dealing with optional variables (basic types and enum) #81

@jimmyti

Description

@jimmyti

I am learning how to use Genome, and so far I am impressed with the flexibility offered by Genome. 👍

  1. 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?
  2. An extension to this question is how do I specify the transformToNode and transformFromNode functions for these optional variables?
  3. 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"]
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions