Specta Swift
A Rust crate for exporting Rust types to Swift, built on top of Specta. Generate idiomatic Swift code from your Rust type definitions with support for complex unions, generics, and nested structures.
Features
- ๐ Zero Runtime Cost - Compile-time type generation
- ๐ฏ Idiomatic Swift - Generates clean, Swift-idiomatic code
- ๐ Complex Unions - Full support for Rust enums with all variant types
- ๐งฌ Generics - Single and multiple generic type parameters
- ๐ Recursive Types - Self-referencing and circular type definitions
- โ๏ธ Highly Configurable - Naming conventions, indentation styles, optional syntax
- ๐ฆ Type Safety - Leverages Specta's robust type introspection
- ๐งช Well Tested - Comprehensive test suite with snapshot testing
- ๐ Special Types - Built-in support for Duration with helper structs
- ๐ Documentation - Preserves and formats Rust doc comments in Swift
- ๐ง Custom Codable - Automatic generation of custom Codable implementations
- ๐จ Protocol Conformance - Support for additional Swift protocols
- ๐ File Export - Direct export to Swift files with custom headers
Quick Start
Add specta-swift to your Cargo.toml:
[]
= { = "2.0", = ["derive"] }
= "0.1"
Define your Rust types:
use ;
use Swift;
Generate Swift code:
This generates:
// This file has been generated by Specta. DO NOT EDIT.
import Foundation
enum ApiResult<T>: Codable {
case success(data: T, status: UInt16)
case error(message: String, code: UInt32)
case loading(progress: Float)
}
struct User: Codable {
let id: UInt32
let name: String
let email: String?
let role: UserRole
}
enum UserRole: Codable {
case guest
case user(permissions: [String])
case admin(level: UInt8, department: String)
}
Advanced Features
Complex Union Types
Specta Swift supports all Rust enum variant types:
Generates:
enum ComplexUnion: Codable {
case none
case tuple(String, UInt32, Bool)
case namedfields(id: UInt32, name: String, active: Bool)
case userstruct(User)
case usertype(UserType)
case complex(user: User, metadata: [String], settings: Admin?)
}
Generic Types
Full support for generic types with multiple parameters:
Recursive Types
Self-referencing types are fully supported:
Configuration
Naming Conventions
use ;
// PascalCase (default)
let swift = default;
// camelCase
let swift = new.naming;
// snake_case
let swift = new.naming;
Optional Styles
use ;
// T? syntax (default)
let swift = default;
// Optional<T> syntax
let swift = new.optionals;
Indentation Styles
use ;
// 4 spaces (default)
let swift = default;
// 2 spaces
let swift = new.indent;
// Tabs
let swift = new.indent;
Custom Headers
let swift = new
.header
.naming;
Additional Protocols
let swift = new
.add_protocol
.add_protocol
.add_protocol;
Serde Integration
let swift = new
.with_serde // Adds import Codable and validation
.add_protocol;
Type Mapping
| Rust Type | Swift Type | Notes |
|---|---|---|
i8, i16, i32, i64 |
Int8, Int16, Int32, Int64 |
Signed integers |
u8, u16, u32, u64 |
UInt8, UInt16, UInt32, UInt64 |
Unsigned integers |
f32, f64 |
Float, Double |
Floating point numbers |
bool |
Bool |
Boolean values |
char |
Character |
Single Unicode character |
String |
String |
UTF-8 strings |
Option<T> |
T? or Optional<T> |
Optional values (configurable) |
Vec<T> |
[T] |
Arrays |
Vec<Vec<T>> |
[[T]] |
Nested arrays |
HashMap<K, V> |
[K: V] |
Dictionaries |
(T, U) |
(T, U) |
Tuples |
std::time::Duration |
RustDuration + helper |
With automatic helper struct |
struct |
struct |
Structures |
enum |
enum |
Enums with custom Codable |
Special Features
Duration Support
std::time::Duration types are automatically converted to a RustDuration helper struct:
Generates:
// MARK: - Duration Helper
public struct RustDuration: Codable {
public let secs: UInt64
public let nanos: UInt32
public var timeInterval: TimeInterval {
return Double(secs) + Double(nanos) / 1_000_000_000.0
}
}
public struct Metrics: Codable {
public let processingTime: RustDuration
public let timeout: RustDuration
}
Documentation Support
Rust doc comments are preserved and formatted for Swift:
/// A comprehensive user account
///
/// This struct represents a complete user account with all necessary
/// information for authentication and personalization.
///
/// # Security Notes
/// - The password field should never be logged
/// - All timestamps are in UTC
Generates:
/// A comprehensive user account
///
/// This struct represents a complete user account with all necessary
/// information for authentication and personalization.
///
/// # Security Notes
/// - The password field should never be logged
/// - All timestamps are in UTC
public struct User: Codable {
/// Unique identifier
public let id: UInt32
/// User's display name
public let name: String
}
Examples
Check out the examples/ directory for comprehensive examples:
basic_types.rs- Basic primitive types and their Swift equivalentsadvanced_unions.rs- Complex enum scenarios and custom Codable implementationsconfiguration_options.rs- All Swift exporter configuration settingsspecial_types.rs- Duration types and special type handlingstring_enums.rs- String enums and custom Codable patternscomprehensive_demo.rs- Complete feature showcase (28 types!)simple_usage.rs- Quick start examplecomments_example.rs- Documentation and comment support
Run any example:
Generated Swift files are saved to examples/generated/ for inspection.
Testing
Run the test suite:
The test suite includes:
- Basic type generation tests
- Comprehensive union type tests
- Advanced recursive type tests
- Duration type mapping tests
- Custom Codable implementation tests
- Configuration option tests
- Snapshot testing for generated code
- String enum handling tests
- Generic type parameter tests
Contributing
Contributions are welcome! Please see the main Specta repository for contribution guidelines.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Related Projects
- Specta - Core type introspection library
- Specta TypeScript - TypeScript exporter
- Specta Go - Go exporter