Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ extension EnumSwitcherVariable {
generatedCode
}
} else {
preSyntax("\(values.first!)")
"break"
}
}
Expand Down
99 changes: 99 additions & 0 deletions Tests/MetaCodableTests/CodedAt/CodedAtEnumTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -802,4 +802,103 @@ struct CodedAtEnumTests {
#expect(json["int"] as? Int == 42)
}
}

struct WithoutAssociatedVariables {
@Codable
@CodedAt("type")
enum Foo {
case foo
}

@Test
func expansion() throws {
assertMacroExpansion(
"""
@Codable
@CodedAt("type")
enum Foo {
case foo
}
""",
expandedSource:
"""
enum Foo {
case foo
}

extension Foo: Decodable {
init(from decoder: any Decoder) throws {
var typeContainer: KeyedDecodingContainer<CodingKeys>?
let container = try? decoder.container(keyedBy: CodingKeys.self)
if let container = container {
typeContainer = container
} else {
typeContainer = nil
}
if let typeContainer = typeContainer {
let typeString: String?
do {
typeString = try typeContainer.decodeIfPresent(String.self, forKey: CodingKeys.type) ?? nil
} catch {
typeString = nil
}
if let typeString = typeString {
switch typeString {
case "foo":
self = .foo
return
default:
break
}
}
}
let context = DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Couldn't match any cases."
)
throw DecodingError.typeMismatch(Self.self, context)
}
}

extension Foo: Encodable {
func encode(to encoder: any Encoder) throws {
let container = encoder.container(keyedBy: CodingKeys.self)
var typeContainer = container
switch self {
case .foo:
try typeContainer.encode("foo", forKey: CodingKeys.type)
break
}
}
}

extension Foo {
enum CodingKeys: String, CodingKey {
case type = "type"
}
}
"""
)
}

@Test
func decodingFromJSON() throws {
let jsonStr = """
{
"type": "foo"
}
"""
let jsonData = try #require(jsonStr.data(using: .utf8))
let decoded = try JSONDecoder().decode(Foo.self, from: jsonData)
#expect(decoded == Foo.foo)
}

@Test
func encodingToJSON() throws {
let original = Foo.foo
let encoded = try JSONEncoder().encode(original)
let json = try JSONSerialization.jsonObject(with: encoded) as? [String: Any]
#expect(json?["type"] as? String == "foo")
}
}
}