chinedufn / swift-bridge

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

Support throwing initializers #287

Closed NiwakaDev closed 1 month ago

NiwakaDev commented 1 month 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 1 month ago

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

NiwakaDev commented 1 month ago

@chinedufn Done.

chinedufn commented 1 month ago

Looks great thanks.