Skip to content

Codable conformance modify generated camel-cased Swift fields from serde #2708

@setoelkahfi

Description

@setoelkahfi

I managed to be able to generate the Codable conformance in swift binding (with generate_codable_conformance = true option) with cargo swift, but the generated fields are camelCased by default, so the parsing is failed.:

#[derive(Serialize, Deserialize, Debug, Record)]
#[tsync]
pub struct ContentResponse {
    pub code: i32,
    pub message: String,
    #[serde(rename = "songProviders")] // Doesn't work
    pub song_providers: Vec<SongProvider>,
}

Swift generated code:

public struct ContentResponse {
    public var code: Int32
    public var message: String
    public var songProviders: [SongProvider]

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(code: Int32, message: String, songProviders: [SongProvider]) {
        self.code = code
        self.message = message
        self.songProviders = songProviders
    }
}

#if compiler(>=6)
extension ContentResponse: Sendable {}
#endif


extension ContentResponse: Equatable, Hashable {
    public static func ==(lhs: ContentResponse, rhs: ContentResponse) -> Bool {
        if lhs.code != rhs.code {
            return false
        }
        if lhs.message != rhs.message {
            return false
        }
        if lhs.songProviders != rhs.songProviders {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(code)
        hasher.combine(message)
        hasher.combine(songProviders)
    }
}

extension ContentResponse: Codable {}

That shouldn't be a problem if the Codable conformance provides the CodingKeys that handle said behaviour. Docs.

My uniffi.toml file:

[bindings.swift]
generate_codable_conformance = true

I cannot make the full networking layer of my app work with uniffi with tokio and reqwest, so I'm trying to at least reuse the data model. My setup is that I have a workspace with main package is the network layer (reqwest + tokio + uniffi), and a model crate with the data model used by the main crate:

crate_networking
- crates
   - model
      - src
         Cargo.toml
         uniffi.toml
- CrateNetworking // cargo swift package
- generated // uniffi
- src
Cargo.toml

Any way to keep the snake case field by default?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions