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

DynamicNodeEncoding Doesn't Work with Optional #217

Open
owenzhao opened this issue Apr 6, 2021 · 0 comments
Open

DynamicNodeEncoding Doesn't Work with Optional #217

owenzhao opened this issue Apr 6, 2021 · 0 comments

Comments

@owenzhao
Copy link
Collaborator

owenzhao commented Apr 6, 2021

// 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.

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