Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for DecodingError "Expected to decode Double but found Int instead." #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Sources/InternalFunction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ public enum MoreCodableError: Error {
}

func castOrThrow<T>(_ resultType: T.Type, _ object: Any, error: Error = MoreCodableError.cast) throws -> T {
/// Int literals cannot be cast as a Double using `as?` so `Double(<Int>)` must be used instead.
if let intValue = object as? Int,
let result = Double(intValue) as? T {
return result
}
/// Most `Any` types can be converted using `as?` if they're a compatible type
guard let returnValue = object as? T else {
throw error
}
Expand Down
9 changes: 9 additions & 0 deletions Tests/DictionaryDecoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ class DictionaryDecoderTests: XCTestCase {
}
XCTAssertEqual(try decoder.decode(Model.self, from: ["date": 13]), Model(date: date, optionalDate: nil))
}

/// JSON has only one Number type, and allows "5" to be considered a Double, not just "5.0"
/// - seealso: https://www.json.org/img/number.png
func testNumberToDouble() throws {
struct Model: Codable, Equatable {
let double: Double?
}
XCTAssertEqual(try decoder.decode(Model.self, from: ["double": 5]), Model(double: 5))
}
}

#if os(Linux)
Expand Down