Skip to content

Commit

Permalink
Replace decodeIfPresent with decode for singleValue (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikhailmaslo authored Dec 15, 2024
1 parent 59612c1 commit 4491fcd
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 9 deletions.
10 changes: 9 additions & 1 deletion Sources/Macro/Misc/CodableBuilders/CodableBuildersMisc.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,17 @@ struct FunctionBuilder: CodeBuildable {

let name: String
let parameters: Params
let isOptionalTry: Bool

init(name: String, parameters: Params, isOptionalTry: Bool = false) {
self.name = name
self.parameters = parameters
self.isOptionalTry = isOptionalTry
}

func build() -> String {
"try \(name)(\(parameters.map { ($0.0.map { "\($0): " } ?? "") + $0.1 }.joined(separator: ",")))"
let tryKeyword = isOptionalTry ? "try?" : "try"
return "\(tryKeyword) \(name)(\(parameters.map { ($0.0.map { "\($0): " } ?? "") + $0.1 }.joined(separator: ",")))"
}
}

Expand Down
18 changes: 12 additions & 6 deletions Sources/Macro/Misc/CodableBuilders/DecodableBuilder+Instance.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,17 +118,23 @@ extension DecodableBuilder {
(nil, type.typeDescription(preservingOptional: false)),
]

let name: String
switch strategy {
case .singleValue:
break
function = FunctionBuilder(
name: "container.decode",
parameters: parameters,
isOptionalTry: type.isOptional
)
case .codingKeys:
name = type.isOptional ? "container.decodeIfPresent" : "container.decode"
parameters.append(("forKey", ".\(identifier)"))
}

function = FunctionBuilder(
name: type.isOptional ? "container.decodeIfPresent" : "container.decode",
parameters: parameters
)
function = FunctionBuilder(
name: name,
parameters: parameters
)
}
}

return DecodableBuilder.BuildingData.Item(identifier: identifier, function: function.build())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ final class AllOfCodableMacroTests: XCTestCase {
extension Example__testing__: Decodable, Encodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.brand = try container.decodeIfPresent(Brand.self)
self.brand = try? container.decode(Brand.self)
self.company = try container.decode(Company.self)
}
func encode(to encoder: Encoder) throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ final class AllOfDecodableMacroTests: XCTestCase {
extension Example__testing__: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.brand = try container.decodeIfPresent(Brand.self)
self.brand = try? container.decode(Brand.self)
self.company = try container.decode(Company.self)
}
}
Expand Down

0 comments on commit 4491fcd

Please sign in to comment.