Skip to content

Commit

Permalink
Fix decoding of enum with associated values when enum case does not c…
Browse files Browse the repository at this point in the history
…ontain value
  • Loading branch information
Alkenso committed Apr 26, 2023
1 parent 666227d commit 2cba711
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Sources/XMLCoder/Decoder/XMLKeyedDecodingContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,13 @@ struct XMLKeyedDecodingContainer<K: CodingKey>: KeyedDecodingContainerProtocol {
referencing: decoder,
wrapping: SharedBox(keyedContainer)
)
} else if let singleBox = value as? SingleKeyedBox {
let element = (singleBox.key, singleBox.element)
let keyedContainer = KeyedBox(elements: [element], attributes: [])
container = XMLKeyedDecodingContainer<NestedKey>(
referencing: decoder,
wrapping: SharedBox(keyedContainer)
)
} else {
throw DecodingError.typeMismatch(
at: codingPath,
Expand Down
19 changes: 19 additions & 0 deletions Tests/XMLCoderTests/AdvancedFeatures/SimpleChoiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,23 @@ final class SimpleChoiceTests: XCTestCase {
let decoded = try XMLDecoder().decode([[IntOrString]].self, from: encoded)
XCTAssertEqual(original, decoded)
}

func testMixedChoice() throws {
enum Choice: Equatable, Codable {
case one
case two(Int)
case three(String, value: Int)
}

struct Foo: Equatable, Codable {
var one = Choice.one
var two = Choice.two(10)
var three = Choice.three("qq", value: 20)
}

let original = Foo()
let encoded = try XMLEncoder().encode(original, withRootKey: "container")
let decoded = try XMLDecoder().decode(Foo.self, from: encoded)
XCTAssertEqual(original, decoded)
}
}

0 comments on commit 2cba711

Please sign in to comment.