diff --git a/Sources/Tagged/Tagged.swift b/Sources/Tagged/Tagged.swift index e3d57aa..cfcfb50 100644 --- a/Sources/Tagged/Tagged.swift +++ b/Sources/Tagged/Tagged.swift @@ -89,6 +89,21 @@ extension Tagged: Encodable where RawValue: Encodable { } } +#if swift(>=5.6) + @available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) + extension Tagged: CodingKeyRepresentable where RawValue: CodingKeyRepresentable { + public init?(codingKey: T) { + guard let rawValue = RawValue(codingKey: codingKey) + else { return nil } + self.init(rawValue: rawValue) + } + + public var codingKey: CodingKey { + self.rawValue.codingKey + } + } +#endif + extension Tagged: Equatable where RawValue: Equatable {} extension Tagged: Error where RawValue: Error {} diff --git a/Tests/TaggedTests/TaggedTests.swift b/Tests/TaggedTests/TaggedTests.swift index 0fc1416..a36fa94 100644 --- a/Tests/TaggedTests/TaggedTests.swift +++ b/Tests/TaggedTests/TaggedTests.swift @@ -70,6 +70,19 @@ final class TaggedTests: XCTestCase { ) } + #if swift(>=5.6) + func testCodingKeyRepresentable() { + if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { + enum Key {} + let xs: [Tagged: String] = [Tagged("Hello"): "World"] + XCTAssertEqual( + String(decoding: try JSONEncoder().encode(xs), as: UTF8.self), + #"{"Hello":"World"}"# + ) + } + } + #endif + func testEquatable() { XCTAssertEqual(Tagged(rawValue: 1), Tagged(rawValue: 1)) }