Skip to content

Commit

Permalink
Assign to properties with explicit self in init(from decoder:)
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjbeaumont committed Dec 10, 2024
1 parent f1d7d8b commit 4fd3eac
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ extension FileTranslator {
let assignExprs: [Expression] = properties.map { property in
let typeUsage = property.typeUsage
return .assignment(
left: .identifierPattern(property.swiftSafeName),
left: .identifierPattern("self").dot(property.swiftSafeName),
right: .try(
.identifierPattern("container").dot("decode\(typeUsage.isOptional ? "IfPresent" : "")")
.call([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ public enum Components {
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
foo = try container.decodeIfPresent(
self.foo = try container.decodeIfPresent(
Swift.String.self,
forKey: .foo
)
Expand Down Expand Up @@ -562,7 +562,7 @@ public enum Components {
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
foo = try container.decodeIfPresent(
self.foo = try container.decodeIfPresent(
Swift.String.self,
forKey: .foo
)
Expand Down Expand Up @@ -602,7 +602,7 @@ public enum Components {
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
foo = try container.decodeIfPresent(
self.foo = try container.decodeIfPresent(
Swift.String.self,
forKey: .foo
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -510,15 +510,30 @@ final class SnippetBasedReferenceTests: XCTestCase {
schemas:
MyObject:
type: object
properties: {}
properties:
id:
type: string
additionalProperties: false
""",
"""
public enum Schemas {
public struct MyObject: Codable, Hashable, Sendable {
public init() {}
public var id: Swift.String?
public init(id: Swift.String? = nil) {
self.id = id
}
public enum CodingKeys: String, CodingKey {
case id
}
public init(from decoder: any Decoder) throws {
try decoder.ensureNoAdditionalProperties(knownKeys: [])
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(
Swift.String.self,
forKey: .id
)
try decoder.ensureNoAdditionalProperties(knownKeys: [
"id"
])
}
}
}
Expand Down

0 comments on commit 4fd3eac

Please sign in to comment.