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

How do I automatically implement protocols/extensions/conformance in Swift? #1905

Open
boehs opened this issue Dec 19, 2023 · 0 comments
Open

Comments

@boehs
Copy link

boehs commented Dec 19, 2023

I have many structs and enums that need to be Codable, among others. Right now, what I do is I have mirror types named FFI* and funcs for conversion:

// shared.swift

// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
public enum FfiReviewUpvoteStatus {
    case upvote
    case neutral
    case downvote
}

// otherCode.swift

enum ReviewUpvoteStatus: Hashable, Codable {
    case upvote, downvote, neutral
    
    init(ffi: FfiReviewUpvoteStatus) {
        self = switch ffi {
            case .upvote:
                Self.upvote
            case .downvote:
                Self.downvote
            case .neutral:
                Self.neutral
        }
    }
}

Automatic synthesis got you covered when they are there on initialization, but if you somewhere else write an extension to conform

// otherCode.swift
extension FfiReviewUpvoteStatus: Codable {} // Extension outside of file declaring enum 'FfiReviewUpvoteStatus' prevents automatic synthesis of 'encode(to:)' for protocol 'Encodable'

It doesn't go so well. Implementing these manually inside an extension is forbidingly difficult. One potential thing I considered is just finding and replacing the output swift but come on ;) Maybe some sort of macro like

#[derive(Debug, uniffi::Enum)]
#[uniffi::implements(swift("Codable"))]
pub enum FFIReviewUpvoteStatus {
    Upvote,
    Neutral,
    Downvote,
}

akin to serde?

Edit: it might also just be possible to add Codable to everything. Worth looking into if that incurs an expense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant