Skip to content

DynamicNodeEncoding Doesn't Work with Optional #217

Open
@owenzhao

Description

@owenzhao
// Model

class Bar:Codable, DynamicNodeEncoding {
    enum CodingKeys: String, CodingKey {
        case id
    }

    static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding {
        switch key {
        case CodingKeys.id:
            return .attribute
        default:
            return .element
        }
    }

    var id = Int.random(in: 1...1000_000)
}
// code

    override func viewDidLoad() {
        super.viewDidLoad()

        
        let bar = Bar()
        output(bar)
        
        print()
        
        let foo:Bar? = bar
        output(foo)
    }
    
    private func output<T:Encodable>(_ t:T) {
        let encoder = XMLEncoder()
        encoder.outputFormatting = .prettyPrinted
        let encodedXML = try! encoder.encode(t, withRootKey: "bar")

        let str = String(data: encodedXML, encoding: .utf8)
        print(str!)
    }
// result

<bar id="974440" />

<bar>
    <id>974440</id>
</bar>

As you can see from the results, they were different. We expected they should be the same.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions