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

Support enums with named data #175

Merged
merged 7 commits into from
Feb 21, 2023

Conversation

NiwakaDev
Copy link
Collaborator

@NiwakaDev NiwakaDev commented Feb 21, 2023

This PR addresses #160 and adds support for enums with named data.

Here's an example of using this.

#[swift_bridge::bridge]
mod ffi {
    enum EnumWithNamedData {
        Variant1 { hello: String, data_u8: u8 },
        Variant2 { data_i32: i32 },
        Variant3,
    }

    extern "Rust" {
        fn reflect_enum_with_named_data(arg: EnumWithNamedData) -> EnumWithNamedData;
    }
}
func testEnumWithNamedData() {
    let enumWithNamedData1 = EnumWithNamedData.Variant1(hello: create_string("hello"), data_u8: 123)
    switch reflect_enum_with_named_data(enumWithNamedData1) {
    case .Variant1(let hello, let dataU8):
        XCTAssertEqual(hello.toString(), "hello")
        XCTAssertEqual(dataU8, 123)
    default:
        XCTFail()
    }
}

@chinedufn
Copy link
Owner

Mind surrounding your Rust example in a bridge module?

#[swift_bridge::bridge]
mod ffi {
    // ... 
}

Copy link
Owner

@chinedufn chinedufn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work. One minor piece of feedback but otherwise looks good to me.

Thanks!

@@ -38,6 +38,20 @@ impl NormalizedStructField {
}
}

/// Used when we want to avoid putting spaces at all between the field name and the colon.
Copy link
Owner

@chinedufn chinedufn Feb 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be clearer to do all of the field setting here instead of doing half of it here an half of it at the call site.

Maybe something like:

/// Create a string for setting the value of a struct's field.
///
/// Example if named field -> "field_name: someValue".
/// Example if unnamed field -> "someValue".
fn struct_field_setter_string(&self, value: String) -> String {
    match &self.accessor {
        NormalizedStructFieldAccessor::Named(name) => {
            format!("{}: {}", name.to_string(), value)
        }
        NormalizedStructFieldAccessor::Unnamed(_idx) => {
            value
        }
    }
}

@chinedufn chinedufn merged commit 5b7004e into chinedufn:master Feb 21, 2023
@chinedufn
Copy link
Owner

Great stuff. Thanks!

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

Successfully merging this pull request may close these issues.

2 participants