Test Large JSON IDs for iOS on a Cloud Mac
If release regression testing reveals that two orders open the same detail page, do not immediately blame list reuse. Check the order IDs in the API response: if large integers have passed through a binary floating-point intermediate representation, two adjacent IDs may already have collapsed into the same value. Isolating this boundary in standalone Swift tests on a cloud Mac can catch identifier corruption without launching a simulator. These tests verify the data contract; they do not replace checks against server-side records.
Define the identifier contract first
Treat an order ID as an opaque identifier, not a quantity to perform arithmetic on. For this article, the wire-format JSON must use strings containing only ASCII digits, with values from 1 to Int64.max and no leading zeros.
This is an example business contract, not a universal rule for identifiers. If your existing IDs allow leading zeros or exceed this range, adjust the contract and tests. Do not silently strip zeros or truncate values in the client.
The largest integer through which binary double-precision floating point can represent every integer exactly is 9007199254740991. Swift’s Int64 can still store larger integers exactly within its own range, so it is incorrect to claim that “JSON numbers inevitably lose precision in Swift.” What needs acceptance testing is the entire path: generation, forwarding, decoding, and persistence.
Converting to a string can only preserve information that has not already been lost. Switching the client to
Stringcannot recover an ID that was rounded upstream.
Create a standalone test package
On a node with the development toolchain already selected, run the following commands to create a test package with no external dependencies. Before running them, record the compiler version with xcrun swift --version, and use the same version on subsequent nodes.
mkdir IdentifierContract
cd IdentifierContract
swift package init --type library
rm Tests/IdentifierContractTests/IdentifierContractTests.swift
Save the following to Sources/IdentifierContract/IdentifierContract.swift. This type provides strict decoding only; it does not implement encoding. If you need outbound encoding, write a separate implementation and tests that preserve the string representation.
import Foundation
public struct OrderID: Decodable, Equatable {
public let rawValue: String
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let text = try container.decode(String.self)
let bytes = Array(text.utf8)
guard !bytes.isEmpty,
bytes.count <= 19,
bytes.first != 48,
bytes.allSatisfy({ (48...57).contains($0) }),
let value = Int64(text),
value > 0 else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Invalid order identifier"
)
}
rawValue = text
}
}
Checking the length before parsing the range explicitly rejects excessively long input. The ASCII byte check also excludes full-width digits and whitespace. Do not trim before decoding, or invalid data will be cleaned up into a passing sample. The network layer must still enforce the response body size limit; this type does not limit the size of the entire document.
Test adjacent large IDs and invalid formats
Add Tests/IdentifierContractTests/OrderIDTests.swift. These tests use XCTest so they can run directly and assert specific decoding errors.
import Foundation
import XCTest
@testable import IdentifierContract
final class OrderIDTests: XCTestCase {
private func decode(_ json: String) throws -> OrderID {
try JSONDecoder().decode(
OrderID.self,
from: Data(json.utf8)
)
}
func testAdjacentLargeIdentifiersStayDistinct() throws {
let a = try decode(#""9007199254740992""#)
let b = try decode(#""9007199254740993""#)
XCTAssertNotEqual(a, b)
XCTAssertEqual(b.rawValue, "9007199254740993")
XCTAssertEqual(
try decode(#""9223372036854775807""#).rawValue,
"9223372036854775807"
)
}
func testInvalidStringsFailValidation() {
let values = [
"", "0", "01", "-1", "+1", "1.0", "1e3",
" 1", "1", "9223372036854775808"
]
for value in values {
let json = "\"\(value)\""
XCTAssertThrowsError(try decode(json), value) { error in
guard case DecodingError.dataCorrupted = error else {
return XCTFail("Unexpected error: \(error)")
}
}
}
}
func testNumericTokenIsRejected() {
XCTAssertThrowsError(try decode("9007199254740993")) { error in
guard case DecodingError.typeMismatch = error else {
return XCTFail("Unexpected error: \(error)")
}
}
}
}
Run swift test; all tests should pass. The adjacent large values check that distinct identities do not collapse into one, the upper-bound sample checks the range, and the numeric token checks the transport type. Do not merely assert that “an error occurred.” Distinguishing type errors from content errors makes it easier to diagnose an API that reverts to a numeric format.
Put real API responses through the same path
Use OrderID for the order ID field in the actual response model, then load sanitized raw JSON fixtures. Preserve each field’s original type. Do not first parse the response into a generic dictionary, convert the numbers, and then generate the test file.
Acceptance testing should cover at least these checks:
- Two adjacent large IDs in the same batch remain distinct after decoding.
- The detail request parameter exactly matches the decoded
rawValue. - The identifier’s bytes remain unchanged after saving locally and reading it back.
- List deduplication, cache keys, and detail navigation all use the same identifier.
- The original server records, outbound responses, and client results match item by item.
Client-side checks alone cannot prove that upstream rounding has not occurred. Seed the test data source with known IDs and compare them against the outbound response. If the source records differ but the response values are identical, trace the problem further upstream to the generator or gateway rather than trying to fix it in the UI layer.
Make legacy API migration a release gate
If a legacy API still returns numbers, first have the server add a string field, make the client prefer it, and then remove the old field according to the API version. If accepting integers is unavoidable during the compatibility period, create a separate adapter that decodes integers directly and checks their range. Do not pass them through Double, and do not hide compatibility logic inside the strict type.
If the old and new fields disagree, block that record from subsequent write operations and log a diagnostic category that does not contain the full business identifier. Silently choosing one value and continuing the submission can turn a read error into an unintended data modification.
For every API upgrade, retain the toolchain version, contract version, test exit code, and names of failing samples. Use the same fixtures across all nodes; do not randomly generate IDs based on the current time. The final release gate is not “the page opens.” It is that the original ID, decoded value, persisted value, and outbound parameter remain identical throughout the path, while invalid formats fail consistently.
Frequently asked questions
Can converting a decoded number to a string restore precision?
No. If an earlier stage rounded the number, converting it to text preserves the wrong value. Compare the raw response with the source record and transmit identifiers as strings from the start.
Why use string identifiers when Swift supports Int64?
Int64 represents integers exactly within its range, but intermediate systems may use floating-point numbers. A string contract avoids that risk and explicitly rejects decimal and exponent notation.
Rent a dedicated Mac for your release window
Choose a model, location, and rental term, then distribute independent regression tests across multiple physical Mac minis. Each node has its own rental term and stops when it expires unless renewed.
Choose a model and rental term