chinedufn / swift-bridge

swift-bridge facilitates Rust and Swift interop.
https://chinedufn.github.io/swift-bridge
Apache License 2.0
842 stars 62 forks source link

Support throwing initializers #287

Closed NiwakaDev closed 3 months ago

NiwakaDev commented 3 months ago

This PR implements throwing initializers. See: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/errorhandling/.

Here's an example of using this feature:

// Rust
#[swift_bridge::bridge]
mod ffi {
    enum ResultTransparentEnum {
        NamedField { data: i32 },
        UnnamedFields(u8, String),
        NoFields,
    }
    extern "Rust" {
        type ThrowingInitializer;
        #[swift_bridge(init)]
        fn new(succeed: bool) -> Result<ThrowingInitializer, ResultTransparentEnum>;
        fn val(&self) -> i32;
    }
}
// Swift
do {
    let throwingInitializer = try ThrowingInitializer(false)
} catch let error as ResultTransparentEnum {
    //...
} catch {
    //...
}
chinedufn commented 3 months ago

Great work on this. Looks good. Left some minor feedback.

NiwakaDev commented 3 months ago

@chinedufn Done.

chinedufn commented 3 months ago

Looks great thanks.