Skip to content

Instantly share code, notes, and snippets.

@ionel71089
Last active April 28, 2023 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ionel71089/aea93aadfb82abdab7bb421c37f80bd7 to your computer and use it in GitHub Desktop.
Save ionel71089/aea93aadfb82abdab7bb421c37f80bd7 to your computer and use it in GitHub Desktop.
import Foundation
@propertyWrapper
struct StringRepresentation<T: LosslessStringConvertible> {
private var value: T?
var wrappedValue: T? {
get {
return value
}
set {
value = newValue
}
}
}
extension StringRepresentation: Codable {
init(from decoder: Decoder) throws {
let string = try? String(from: decoder)
value = string.flatMap(T.init)
}
func encode(to encoder: Encoder) throws {
if let value = value {
try "\(value)".encode(to: encoder)
} else {
// encodes to null, or {} if commented
try Optional<String>.none.encode(to: encoder)
}
}
}
struct Test {
// A
@StringRepresentation
var value: Double?
}
extension Test: Codable {
// B
// enum CodingKeys: String, CodingKey {
// case value
// }
//
// init(from decoder: Decoder) throws {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// let string = try container.decodeIfPresent(String.self, forKey: .value)
// value = string.flatMap(Double.init)
// }
//
// func encode(to encoder: Encoder) throws {
// var container = encoder.container(keyedBy: CodingKeys.self)
// if let value = value {
// try container.encode("\(value)", forKey: .value)
// }
// }
}
// A and B should be equivalent
func testDecodeValue() -> Bool {
print("\n\(#function)")
let json = """
{
"value": "12.0"
}
""".data(using: .utf8)!
let test: Test?
do {
test = try JSONDecoder().decode(Test.self, from: json)
} catch {
print(error)
return false
}
return test?.value == 12.0
}
func testDecodeMissingValue() -> Bool {
print("\n\(#function)")
let json = """
{
}
""".data(using: .utf8)!
let test: Test?
do {
test = try JSONDecoder().decode(Test.self, from: json)
} catch {
print(error)
return false
}
return test?.value == nil
}
func testEncodeValue() -> Bool {
print("\n\(#function)")
var test = Test()
test.value = 12.0
do {
let json = String(data: try JSONEncoder().encode(test), encoding: .utf8) ?? ""
print(json)
return json == "{\"value\":\"12.0\"}"
} catch {
print(error)
return false
}
}
func testEncodeMissingValue() -> Bool {
print("\n\(#function)")
var test = Test()
test.value = nil
do {
let json = String(data: try JSONEncoder().encode(test), encoding: .utf8) ?? ""
print(json)
return json == "{}"
} catch {
print(error)
return false
}
}
print(testDecodeValue())
print(testDecodeMissingValue())
print(testEncodeValue())
print(testEncodeMissingValue())
@alexj70
Copy link

alexj70 commented Apr 28, 2023

Hi. testDecodeMissingValue doesn't work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment