Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoding Elements with Property wrappers doesn't work #279

Open
janvhs opened this issue Dec 16, 2023 · 0 comments
Open

Decoding Elements with Property wrappers doesn't work #279

janvhs opened this issue Dec 16, 2023 · 0 comments

Comments

@janvhs
Copy link

janvhs commented Dec 16, 2023

There seems to be a problem decoding annotated struct members into arrays.

When decoding a struct with the DynamicNodeDecoding protocol, it decodes correctly, but when using @ Element, it doesn't.

To highlight the problem, I typed up the following example.

import Foundation
import XMLCoder // .package(url: "https://github.com/CoreOffice/XMLCoder.git", from: "0.17.1")

struct WorkingRoot: Codable, DynamicNodeDecoding, DynamicNodeEncoding {
    var nodes: [String]

    enum CodingKeys: String, CodingKey {
        case nodes
    }

    static func nodeDecoding(for key: CodingKey) -> XMLCoder.XMLDecoder.NodeDecoding {
        switch key {
        case WorkingRoot.CodingKeys.nodes: .element
        default: .elementOrAttribute
        }
    }

    static func nodeEncoding(for key: CodingKey) -> XMLCoder.XMLEncoder.NodeEncoding {
        switch key {
        case WorkingRoot.CodingKeys.nodes: .element
        default: .element
        }
    }
}

struct FailedRoot: Codable {
    @Element var nodes: [String]
}

// struct Node: Codable {
//     @Attribute var attr: String?
//     @Element var value: String
//
//     enum CodingKeys: String, CodingKey {
//         case attr
//         case value = ""
//     }
// }

let xml = """
<root>
    <nodes attr="test">
        First
    </nodes>
    <nodes>
        Second
    </nodes>
    <nodes>
        Third
    </nodes>
</root>
"""

let testContents = xml.data(using: .utf8)!

// This uses the DynamicNodeDecoding and DynamicNodeEncoding protocols and is working as expected.
let correctDecoded: WorkingRoot = try XMLDecoder().decode(WorkingRoot.self, from: testContents)

// This uses the @Element decorator and doesn't decode correctly.
let wrongDecoded: FailedRoot = try XMLDecoder().decode(FailedRoot.self, from: testContents)

print("This is fine")
print(correctDecoded) // WorkingRoot(nodes: ["First", "Second", "Third"])
print()
print("This isn't")
print(wrongDecoded) // FailedRoot(_nodes: XMLCoder.Element<Swift.Array<Swift.String>>(wrappedValue: ["First"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant