Skip to content

Commit

Permalink
Fully support Optional Int64 and UInt64 for JSONString
Browse files Browse the repository at this point in the history
  • Loading branch information
patmalt committed Feb 25, 2021
1 parent 17d3e71 commit 45b0115
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
19 changes: 16 additions & 3 deletions wire-library/wire-runtime-swift/src/main/swift/JSONString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,18 @@ public struct JSONString<T : Hashable> : Hashable, Codable {
switch T.self {
case is Int64.Type, is Optional<Int64>.Type:
let container = try decoder.singleValueContainer()
self.wrappedValue = Int64(try container.decode(String.self))! as! T
if let value = try? container.decode(String.self) {
self.wrappedValue = Int64(value)! as! T
} else {
self.wrappedValue = Optional<Int64>.none as! T
}
case is UInt64.Type, is Optional<UInt64>.Type:
let container = try decoder.singleValueContainer()
self.wrappedValue = UInt64(try container.decode(String.self))! as! T
if let value = try? container.decode(String.self) {
self.wrappedValue = UInt64(value)! as! T
} else {
self.wrappedValue = Optional<UInt64>.none as! T
}
case is [Int64].Type:
var container = try decoder.unkeyedContainer()
var array: [Int64] = []
Expand Down Expand Up @@ -66,7 +74,12 @@ public struct JSONString<T : Hashable> : Hashable, Codable {
try container.encode(String(value))
}
default:
fatalError("Unsupported type \(T.self)")
if T.self is Optional<Int64>.Type || T.self is Optional<UInt64>.Type {
var container = encoder.singleValueContainer()
try container.encodeNil()
} else {
fatalError("Unsupported type \(T.self)")
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,32 +28,48 @@ final class JsonStringTests: XCTestCase {
var c: [Int64]
@JSONString
var d: [UInt64]
@JSONString
var e: Int64?
@JSONString
var f: Int64?
@JSONString
var g: UInt64?
@JSONString
var h: UInt64?
}

func testSupportedTypes() throws {
let expectedStruct = SupportedTypes(
a: -12,
b: 13,
c: [-14],
d: [15]
d: [15],
e: -16,
f: nil,
g: 17,
h: nil
)
let expectedJson = """
{\
"a":"-12",\
"b":"13",\
"c":["-14"],\
"d":["15"]\
"d":["15"],\
"e":"-16",\
"f":null,\
"g":"17",\
"h":null\
}
"""

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys // For deterministic output.

let jsonData = try! encoder.encode(expectedStruct)
let jsonData = try encoder.encode(expectedStruct)
let actualJson = String(data: jsonData, encoding: .utf8)!
XCTAssertEqual(expectedJson, actualJson)

let actualStruct = try! JSONDecoder().decode(SupportedTypes.self, from: jsonData)
let actualStruct = try JSONDecoder().decode(SupportedTypes.self, from: jsonData)
XCTAssertEqual(expectedStruct, actualStruct)
}
}

0 comments on commit 45b0115

Please sign in to comment.