Skip to content

IntDecodingStrategy

Compare
Choose a tag to compare
@swhitty swhitty released this 27 Jun 23:37
· 26 commits to main since this release
b542a92

The decoding of BinaryInteger types (Int, UInt etc) can now be adjusted via intDecodingStrategy.

The default strategy IntDecodingStrategy.exact is the previous behaviour and ensures the source value is exactly represented by the decoded type allowing floating point values with no fractional part to be decoded:

// [10, 20, -30, 50]
let values = try KeyValueDecoder().decode([Int8].self, from: [10, 20.0, -30.0, Int64(50)])

// throws DecodingError.typeMismatch because 1000 cannot be exactly represented by Int8
_ = try KeyValueDecoder().decode(Int8.self, from: 1000])

Values with a fractional part can also be decoded to integers by rounding with any FloatingPointRoundingRule:

let decoder = KeyValueDecoder()
decoder.intDecodingStrategy = .rounding(rule: .toNearestOrAwayFromZero)

// [10, -21, 50]
let values = try decoder.decode([Int].self, from: [10.1, -20.9, 50.00001]),

Values can also be clamped to the representable range:

let decoder = KeyValueDecoder()
decoder.intDecodingStrategy = .clamping(roundingRule: .toNearestOrAwayFromZero)

// [10, 21, 127, -128]
let values = try decoder.decode([Int8].self, from: [10, 20.5, 1000, -Double.infinity])

Many thanks to @eun-ice for the suggestion.