glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
11.76k stars 1.04k forks source link

[FEATURE]: Swift - Sendable JSONAny #2598

Open gnrcampos opened 1 month ago

gnrcampos commented 1 month ago

Context (Input, Language)

Output Language: Swift

Description

With the push for sendable adherence from Apple I want to suggest we change the approach to the JSONAny object that would make it adhere to the protocol (and possibly to other important protocols like Equatable and Hashable if need be).

Current Behaviour / Output

class JSONAny: Codable {
    let value: Any
    ...
}

Proposed Behaviour / Output

enum JSONAny: Codable, Sendable {
    case null
    case bool(Bool)
    case int(Int64)
    case double(Double)
    case string(String)
    case array([Self])
    case dictionary([String: Self])
    ...
}

Solution

The solution would be to change the implementation to make it an enum with associated values instead of a class with a let value Any. For backwards compatibility purposes we can create a computed attribute that returns the old Any such as:

var value: Any {
    switch self {
    case .null:
        return JSONNull()
    case let .bool(value):
        return value
    case let .int(value):
        return value
    case let .double(value):
        return value
    case let .string(value):
        return value
    case let .array(array):
        return array.map { $0.value }
    case let .dictionary(dictionary):
        return dictionary.mapValues { $0.value }
    }
}

And an initializer that takes the value: Any as a parameter.

There are caveats such as the fact that this wouldn't work with ObjC support but we can have branching logic to keep the current implementation in this case.

I'm more than happy to create a PR for this but wanted to check with the community first to see if I'm missing anything.

Thanks in advance!

niklassaers commented 3 weeks ago

Cleaning up these "'Any' does not conform to the 'Sendable' protocol" errors would be great :-) I'd be happy to review your PR