Skip to content

Converting an integer literal in JSON to a Double can't be done with as? #21

@andrewash

Description

@andrewash

Hi! Longtime fan over here =)
I've found a bug that I've traced to func castOrThrow<T>(_ resultType: T.Type, _ object: Any, error: Error = MoreCodableError.cast) throws -> T

The error I'm seeing is: "Expected to decode Double but found Int instead"
I'm decoding with DictionaryDecoding, and my dictionary looks like this:

[
    "id": "some_random_uuid_string",
    "name": "James Bond",
    "fps": 30,
    "resolution": "1080p",
    "captureDuration": 15
]

The model defines var captureDuration: Double
I'd like it to be a Double because I want to support half-second duration times in the future, like 5.5 seconds
Currently however the JSON has only whole numbers literals like 15, 30, etc.

When I stopped my debugger at func castOrThrow() I see:

(lldb) po object as? Double
nil
(lldb) po 30.0 as? Double
▿ Optional<Double>
  - some : 30.0
(lldb) po 30 as? Double
nil

The first & last lines are the issue.

The correct way to cast an integer literal to a Double is Double(object)

I think this code snippet will ensure integer literals can be decoded as a Double, however I haven't been able to test it:

func castOrThrow<T>(_ resultType: T.Type, _ object: Any, error: Error = MoreCodableError.cast) throws -> T {
    if let intValue = object as? Int,
       let result = Double(intValue) as? T {
        return result
    }
    guard let returnValue = object as? T else {
        throw error
    }

    return returnValue
}

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions