Swift Bindings
UniFFI ships with production-quality support for generating Swift bindings. Concepts from the UDL file map into Swift as follows:
- Primitive datatypes map to their obvious Swift counterpart, e.g.
u32becomesUInt32,stringbecomesString,bytesbecomesData, etc. - An object interface declared as
interface Tis represented as a Swiftprotocol TProtocoland a concrete Swiftclass Tthat conforms to it. Having the protocol declared explicitly can be useful for mocking instances of the class in unittests. - A dictionary struct declared as
dictionary Tis represented as a Swiftstruct Twith public mutable fields. - An enum declared
enum Tor[Enum] interface Tis represented as a Swiftenum Twith appropriate variants. - Optional types are represented using Swift's builtin optional type syntax
T?. - Sequences are represented as Swift arrays, and Maps as Swift dictionaries.
- Errors are represented as Swift enums that conform to the
Errorprotocol. - Function calls that have an associated error type are marked with
throws, and hence must be called using one of Swift'strysyntax variants. - Failing assertions, Rust panics, and other unexpected errors in the generated code
are translated into a private enum conforming to the
Errorprotocol.- If this happens inside a throwing Swift function, it can be caught and handled
by a catch-all
catchstatement (but do so at your own risk, because it indicates that something has gone seriously wrong). - If this happens inside a non-throwing Swift function, it will be converted into a fatal Swift error that cannot be caught.
- If this happens inside a throwing Swift function, it can be caught and handled
by a catch-all
Generated files
UniFFI generates several kinds of files for Swift bindings:
- C header files declaring the FFI structs/functions used by the Rust scaffolding code
- A modulemap, which defines a Swift module for the C FFI definitions in the header file.
- A Swift source file that defines the Swift API used by consumers. This imports the FFI module.
Swift 6 Support
UniFFI has partial support for Swift 6. We would welcome all help improving this.
Sendable
Most generated code will conform to Sendable. Depending on your Swift compiler options,
you may find rough edges where this support doesn't quite exist.
At time of writing, it is known that async code will not conform.
This is being tracked in #2448
Note that Sendable conformance does impose obligations on code you write - for example, when
you implement a Foreign Trait, the "protocol" generated by UniFFI will require Sendable conformance,
therefore your implementation of that protocol must too.
See the Swift documentation for more.