Repository navigation
How Bindings Map
Side-by-side examples of Swift declarations and the C# they generate. These are real patterns from the test suite and validated libraries.
// Swift
public class ImagePipeline {
public static var shared: ImagePipeline { get }
public var configuration: ImagePipeline.Configuration { get }
public init(configuration: ImagePipeline.Configuration)
public func loadImage(_ request: ImageRequest) async -> UIImage
}// Generated C#
public partial class ImagePipeline : ISwiftObject, IDisposable
{
public static ImagePipeline Shared { get; }
public ImagePipeline.Configuration Configuration { get; }
public ImagePipeline(ImagePipeline.Configuration configuration) { ... }
public Task<UIImage> LoadImageAsync(ImageRequest request, CancellationToken cancellationToken = default) { ... }
}Classes use SafeHandle-based ARC. retain on creation, release on Dispose() and on the GC finalizer — so disposal is optional. Use using when you want deterministic cleanup of scarce resources (file handles, caches), the same reason you'd use using on a FileStream. See Ownership.
// Swift
@frozen public struct CGPoint {
public var x: Double
public var y: Double
}// Generated C#
public partial struct CGPoint : ISwiftObject
{
public double X { get; set; }
public double Y { get; set; }
}Frozen structs with only blittable fields become C# struct with matching memory layout.
// Swift
public struct Configuration {
public var maxConcurrentTasks: Int
public var isProgressiveDecodingEnabled: Bool
}// Generated C#
public partial class Configuration : ISwiftObject, IDisposable
{
public nint MaxConcurrentTasks { get; set; }
public bool IsProgressiveDecodingEnabled { get; set; }
}Non-frozen structs become C# class with a SafeHandle payload — their size isn't known at compile time.
// Swift
@frozen public enum Direction {
case north, south, east, west
public func opposite() -> Direction
}// Generated C#
public enum Direction : int
{
North = 0, South = 1, East = 2, West = 3,
}
public static partial class DirectionExtensions
{
public static Direction Opposite(this Direction self) { ... }
}// Swift
public enum Result<T> {
case success(T)
case failure(Error)
}// Generated C#
public partial class Result<T> : ISwiftObject, IDisposable
{
public enum CaseTag : uint { Success = 0, Failure = 1 }
public static Result<T> Success(T value) { ... }
public static Result<T> Failure(SwiftError error) { ... }
public CaseTag Tag { get; }
public bool TryGetSuccess([MaybeNullWhen(false)] out T value) { ... }
public bool TryGetFailure([MaybeNullWhen(false)] out SwiftError value) { ... }
}Switch on Tag to branch by case, or call the TryGet… extractor for the case you expect. It returns false (and a default value) when the instance holds a different case. Cases without a payload get a static instance instead of a factory method. On Mono, Enum.GetValues throws for a CaseTag nested in a generic class such as Result<T>. See Known Limitations for the workaround.
Frozen raw-value enums (both Int and String) project as C# enum value types. String raw-value enums get a pair of helpers (ToRawValue/FromRawValue) that bridge to and from the underlying string values:
// Swift
@frozen public enum LogLevel: String {
case debug, info, warning, error
}// Generated C#
public enum LogLevel
{
Debug,
Info,
Warning,
Error,
}
public static partial class LogLevelExtensions
{
public static string ToRawValue(this LogLevel self) { ... }
public static LogLevel? FromRawValue(string rawValue) { ... }
}Int-raw-value enums map directly to a C# enum with a long underlying type (matching Swift's 64-bit Int) and don't need the ToRawValue/FromRawValue helpers — the enum's underlying value is the raw value.
// Swift (pure Swift protocol — uses witness table dispatch for callers)
public protocol ImageProcessing {
var identifier: String { get }
func process(_ image: UIImage) -> UIImage?
}
// Swift consumer expecting the protocol existential
public func runPipeline(_ processor: any ImageProcessing) -> UIImage? {
processor.process(UIImage())
}// Generated C# — interface (for consuming Swift implementations)
public interface IImageProcessing
{
string Identifier { get; }
UIImage? Process(UIImage image);
}
// Generated C# — proxy (for providing C# implementations to Swift)
public partial class ImageProcessingProxy : IImageProcessing, ISwiftObject, IDisposable
{
public ImageProcessingProxy(IImageProcessing implementation) { ... }
}Consuming a Swift implementation (witness dispatch path):
// Assume Swift code returns an existential or you receive one via API
IImageProcessing processor = /* obtained from Swift, e.g. via factory or property */;
string id = processor.Identifier; // getter → witness dispatch
UIImage? result = processor.Process(someImage); // method → witness dispatch (blittable/String/collection paths)Providing a C# implementation to Swift:
public class MyProcessor : IImageProcessing
{
public string Identifier => "my-processor";
public UIImage? Process(UIImage image) => image; // or more complex work
}
var proxy = new ImageProcessingProxy(new MyProcessor());
// Pass proxy to any Swift API expecting `ImageProcessing`Closure-bearing protocol methods, nested protocols, and @objc optional members (DIMs) are all supported. Witness dispatch P/Invokes are emitted only for dispatchable signatures (see WitnessDispatchEmitter.ClassifyMethodDispatch and Supported Features for the matrix).
Both method signatures and properties use idiomatic C# types.
| Swift | C# |
|---|---|
String |
string |
Array<T> |
IReadOnlyList<T> (return) / IEnumerable<T> (param) |
Set<T> |
IReadOnlySet<T> (both directions) |
Dictionary<K,V> |
IReadOnlyDictionary<K,V> (return) / IDictionary<K,V> (param) |
Optional<T> |
T? |
Int |
nint |
Bool |
bool |
URL |
NSUrl |
Date |
DateTimeOffset |
UUID |
Guid |
Data |
byte[] |
Decimal |
Foundation.NSDecimalNumber |
UnsafeMutableRawBufferPointer |
Span<byte> (sync parameters; not returns or escaping/async positions) |
UnsafeRawBufferPointer |
ReadOnlySpan<byte> (same scope) |
AnyObject |
object (see AnyObject below) |
// Swift
public func search(_ query: String, limit: Int) -> [Result]
public var title: String { get }// Generated C#
public IReadOnlyList<Result> Search(string query, nint limit) { ... }
public string Title { get; }A parameter, return value, property, or subscript typed as AnyObject (or AnyObject & Sendable) binds as object in C#, including initializer parameters. You can pass:
- An instance of a generated Swift class, or a C# class that derives from one.
- An Objective-C object (any
NSObject). - A value returned by an
AnyObjectmember.
Anything else throws ArgumentException before the call reaches Swift, including a plain C# object, a string, a generated Swift struct, and a Core Foundation wrapper such as a CGColor. null throws ArgumentNullException, and a disposed object throws ObjectDisposedException.
A returned AnyObject is an opaque object that holds the Swift reference. It is not an instance of the generated class, so it can't be cast to one. Pass it back to any AnyObject member, and Swift receives the same instance. Dispose it when you are done with it:
object item = cache.Lookup("key");
try { other.Store(item); }
finally { (item as IDisposable)?.Dispose(); }AnyObject? and collections or closures of AnyObject are not bound yet. See Known Limitations.
// Swift
public func onComplete(_ handler: @escaping (Int, Bool) -> Void)
public func transform(_ fn: @escaping (String) -> String) -> String// Generated C#
public void OnComplete(Action<nint, bool> handler) { ... }
public string Transform(Func<string, string> fn) { ... }Closures marshal through GCHandle pinning. The generated code handles the delegate lifecycle automatically.
// Swift
public func attempt(_ action: @escaping () throws -> String)// Generated C# — simplified overload (user-facing)
public void Attempt(Func<string> action) { ... }
// Generated C# — raw overload (hidden via EditorBrowsable)
public void Attempt(Func<SwiftResult<SwiftString, SwiftError>> action) { ... }The simplified overload wraps your Func in a try/catch and converts exceptions to SwiftResult automatically.
// Swift
public func loadImage(_ url: URL) async -> UIImage
public func validate() async throws// Generated C#
public Task<UIImage> LoadImageAsync(NSUrl url, CancellationToken cancellationToken = default) { ... }
public Task ValidateAsync(CancellationToken cancellationToken = default) { ... }Async methods are emitted with the standard CancellationToken cancellationToken = default trailing parameter — including on members that come from a cross-module extension. The generator creates a Swift wrapper function that bridges the async boundary using a @_cdecl callback. The C# side uses TaskCompletionSource<T> to convert the callback into a standard .NET Task. Throwing variants surface SwiftException<TError>. Implementing a Swift async protocol requirement from C# is also supported for primitive shapes — see Supported Features.
Cancelling the token completes the returned Task as Canceled — await throws OperationCanceledException, it does not fault with some other exception:
using var cts = new CancellationTokenSource();
var task = obj.LoadImageAsync(url, cts.Token);
cts.Cancel();
try { var image = await task; }
catch (OperationCanceledException) { /* the canonical .NET shape */ }Two details worth knowing:
-
A token that is already cancelled short-circuits: the binding returns an already-cancelled
Taskwithout calling into Swift at all. -
For a real Swift
asyncmethod the Swift task is also cancelled, by calling Swift'sTask.cancel(). That is Swift's cooperative cancellation, so the Swift function stops early only where it checksTask.isCancelled/Task.checkCancellation()— exactly as it would from Swift. The C#TaskbecomesCanceledimmediately either way, so a Swift function that ignores cancellation keeps running to completion in the background after you have already observed the cancellation.
A Task overload synthesized over a Swift completion-handler API (as opposed to a real Swift async function) is different: there is no Swift task to cancel, so the token cancels the returned Task only and the underlying operation runs to completion. The generated XML doc on the cancellationToken parameter says which one you have.
// Swift
public enum LoadError: Error { case notFound, denied(reason: String) }
public func load(_ id: Int) throws -> Data
public func loadAsync(_ id: Int) async throws -> Data// Generated C# — throws bridge to SwiftException<TError>
try
{
var data = obj.Load(id);
}
catch (SwiftException<LoadError> ex)
{
// ex.Error is the original Swift error value, not a stringified message
if (ex.Error.IsNotFound) { /* ... */ }
}
try
{
var data = await obj.LoadAsync(id);
}
catch (SwiftException<LoadError> ex) { /* ... */ }Plain throws and async throws surface as SwiftException<TError> where TError is the Swift error type. Both the error's identity and its description round-trip: ex.Error is the original typed value when extraction succeeds — pattern-match on case tags and read associated values instead of parsing strings (it falls back to default/null only in the rare case Swift's typed-error cast fails) — and ex.Message carries Swift's localizedDescription / String(describing:). A caught error no longer collapses to a message-only exception.
A thrown error becomes a SwiftException<TError> (above). An error that crosses the boundary as a value — any Error, returned or passed rather than thrown — is different: it surfaces as Swift.Foundation.AnyError, a disposable reference type wrapping the boxed Swift error.
// Swift
public func lastError() -> (any Error)?
public func describe(_ error: any Error) -> String// Generated C#
using AnyError? err = obj.LastError(); // (any Error)? → AnyError? (nullable reference)
if (err is not null)
Console.WriteLine(err.LocalizedDescription);AnyError owns the boxed error's retain and releases it on Dispose()/finalization, so dispose it (or use using) when you take ownership of a returned error — the same rule as any other owned Swift value. Two things to note if you used an earlier preview: (any Error)? is a nullable reference (AnyError?), so test with is null / is not null, not .HasValue/.Value; and AnyError is IDisposable, so the SB1001 analyzer flags an undisposed owned local.
// Swift
public var updates: AsyncStream<Update> { get }
public static var currentEntitlements: Transaction.Transactions { get } // AsyncSequence// Generated C#
public IAsyncEnumerable<Update> Updates { get; }
public static IAsyncEnumerable<VerificationResult<Transaction>> CurrentEntitlements { get; }
// Consume with await foreach
await foreach (var entitlement in Transaction.CurrentEntitlements)
{
// ...
}Swift AsyncSequence-typed members lower to IAsyncEnumerable<T> so await foreach works directly.
A throwing AsyncThrowingStream<T> binds the same way, with two additions: a Swift error thrown by the producer surfaces at the await foreach (catch it like any async throw), and disposing the C# enumerator early — breaking out of the loop, or disposing the IAsyncEnumerator<T> — task-cancels the suspended Swift producer and frees its context handle.
// Swift: public var events: AsyncThrowingStream<Event, Error> { get }
try
{
await foreach (var ev in obj.Events)
{
if (ShouldStop(ev)) break; // cancels the Swift producer, frees its context handle
}
}
catch (SwiftException ex)
{
// the Swift producer threw — ex.Message carries the error's description
}// Swift
public init?(name: String)// Generated C#
public static bool TryCreate(string name, out MyType result) { ... }Failable init? becomes a TryCreate factory with out parameter. Returns false when Swift returns .none.
For raw representable enums specifically, the pattern is FromRawValue:
public static LogLevel? FromRawValue(string rawValue) { ... }// Swift
public subscript(index: Int) -> Element { get }
public subscript(key: String) -> Value? { get set }// Generated C#
public Element this[nint index] { get; }
public Value? this[string key] { get; set; }// Swift
public static func == (lhs: MyType, rhs: MyType) -> Bool
public static func + (lhs: MyType, rhs: MyType) -> MyType// Generated C#
public static bool operator ==(MyType lhs, MyType rhs) { ... }
public static bool operator !=(MyType lhs, MyType rhs) { ... } // auto-synthesized
public static MyType operator +(MyType lhs, MyType rhs) { ... }Comparison operators auto-synthesize their complement (==/!=, </>, <=/>=).
An operator's result may be a value type, a class, an enum, or a bridged type such as String — the result is marshalled to the projected C# type rather than handed back as a raw pointer.
Operators declared on a class do not round-trip at runtime yet. An operator whose parent is a frozen struct gets a C-convention wrapper and works on both runtimes. An operator whose parent is a class compiles, but the class operands cross as handles under the Swift calling convention, which both Mono and NativeAOT reject before the call runs. Until class parents get their own wrappers, call the equivalent named method if the library offers one, or add a Swift shim that takes the operands as parameters. Operators on structs are unaffected.
C# names are derived from the Swift (or Objective-C) declaration by a fixed sequence of rules rather than authored by hand. This section is the one place those rules are written down; per-library guides link here instead of restating them.
The starting point is a plain transliteration — Swift's lowerCamelCase members become PascalCase, and a type keeps the name it was declared under. Every rule below fires only when that starting point is unusable: two members would land on the same C# identifier, the name collides with something else already in scope, or .NET spells that shape differently from Swift.
| Swift shape | C# name | Detail |
|---|---|---|
Member loadImage
|
LoadImage |
plain PascalCase |
init? / init!
|
TryCreate factory with an out parameter |
Failable Initializers |
async member |
…Async, plus a trailing CancellationToken cancellationToken = default
|
Async Methods |
protocol Foo |
interface IFoo
|
Protocols |
| Enum with associated values | class, one static factory per case, Is… / …Value accessors |
Enums with associated values |
| Non-frozen struct | class over a Swift-owned buffer | Non-frozen structs → C# classes, above |
| Extension members on an enum |
{Enum}Extensions static class |
Simple enums |
The Async suffix is appended after the collision rules below have run, so it never hides a collision. One rename runs after it rather than before: a member whose name would collide with a type parameter of its declaring type is resolved on the final name, suffix included — so on a Box<T>, an async t() is already unique as TAsync and is left alone, while a type parameter literally spelled TAsync still forces the rename.
- A zero-argument, noun-shaped async member reads as a getter and takes the
Getprefix —func data() async -> Tbinds asGetDataAsync(). The same member with a parameter keeps the bare name (WeatherAsync(…)). - A
mutatingasync member is not treated as a getter, so an iterator'snext()staysNextAsync. - A leading Swift
asyncprefix is dropped rather than doubled:asyncGetString()binds asGetStringAsync(). - The trailing
CancellationTokenis part of the member's identity, so a Swift type declaring bothfunc foo() asyncandfunc fooAsync()keeps both — one asTask<T> FooAsync(…, CancellationToken), the other as the synchronousFooAsync(…).
Swift distinguishes overloads by argument label; C# does not. When a family of members would collapse onto one C# name, four rungs are tried in order, and the first that separates the whole family wins.
1 — Bare-name ownership. If exactly one member of the family is label-less and reaches the contested spelling naturally, it keeps the bare name and its siblings move on to the next rung. If none or several qualify, nobody owns it.
2 — Argument labels, appended Objective-C-selector style:
// Swift
public func render(alpha: Int32)
public func render(beta: Int32)
public func render(gamma: Int32)// Generated C#
public void RenderAlpha(int alpha) { ... }
public void RenderBeta(int beta) { ... }
public void RenderGamma(int gamma) { ... }The same rung names delegate-style protocol requirements, where the receiver is the unlabelled first parameter — conversationManager(_:didActivate:) and conversationManager(_:didDeactivate:) become ConversationManagerDidActivate and ConversationManagerDidDeactivate.
3 — Swift parameter types, when the labels do not discriminate. The token is built from the Swift type, not the projected C# one:
// Swift
public func transform(_ value: RefBox)
public func transform(_ value: RefBox?)// Generated C#
public void TransformWithRefBox(RefBox value) { ... }
public void TransformWithOptionalRefBox(RefBox? value) { ... }4 — Refusal. When the parameter lists are genuinely identical — members differing only by return type, or true duplicates — there is no faithful name to assign. The later member is dropped rather than numbered, and the binding report records both Swift signatures under DuplicateSignature so you can see what was lost.
Two consequences worth knowing:
-
Overload disambiguation never falls back to a number. The ladder has no numeric rung — it runs out of ideas and refuses instead — and a build gate reads the resolver's own assignment records and fails the build if a numbered overload name ever appears. This is a statement about overloads, not about every name in a binding. Numbers still reach a name through the separate de-collision layer described below, which is not the overload resolver and which the gate does not read: scheme 3 there resolves two Swift names differing only by case (
url/URL→Url/Url2) with a digit on purpose, because a case-only pair carries no semantic difference to derive a token from. If you see a trailing digit, check which layer produced it before reading it as a disambiguated overload. - A name is derived from its whole family, so adding or removing an overload upstream can move a sibling onto a different rung and change its C# name. Treat an overload set's names as tied to the library version you built against.
A name can also collide with a nested type, a sibling property, its own enclosing type, a type parameter of its declaring type, or a member inherited from the BCL. The token tells you which side of the collision moved:
-
Type-side tokens —
Kind,Info. Seeing one means the type was renamed and the member kept its natural name. -
Member-side tokens —
Value,Method,With,Get,Swift. Seeing one means the member was renamed and the type kept its natural name.
The two sets are deliberately disjoint. Six schemes cover the type-vs-member shapes, applied in this order because renaming a type changes what every later rule sees:
| # | Shape | What moves | Example |
|---|---|---|---|
| 1 | A nested type collides with a sibling property of that type | the type, with a kind-aware suffix — Kind for an enum, Info for a struct or class |
Transaction.Offer (struct) → OfferInfo; Transaction.OfferType (enum) → OfferTypeKind
|
| 2 | A type's name differs from a sibling namespace only by case | the type, same kind-aware suffix; the namespace keeps its spelling |
SCANKit beside namespace ScanKit → SCANKitInfo
|
| 3 | Two sibling members' Swift names differ only by case | the later member, numerically |
url / URL → Url / Url2
|
| 4 | A property's name equals its enclosing type's name | the property, Value suffix |
Config.config → ConfigValue
|
| 5 | A method reads as a getter, or equals its enclosing type's name | the method, Get prefix |
Checksum.checksum() → GetChecksum()
|
| 6 | A method's name equals a sibling property's name | the method, Method suffix — or a With prefix when the method returns Self, so a fluent builder stays fluent |
count() beside Count → CountMethod(); equalToSuperview() beside EqualToSuperview → WithEqualToSuperview()
|
Scheme 5 runs before scheme 6 on purpose: an async getter colliding with a property reads GetStatusAsync, not StatusMethodAsync.
Scheme 3 is the only one whose first answer is a number. Two Swift spellings that differ only by case carry no semantic difference to draw a token from, so declaration order decides: the first keeps the natural identifier and later siblings escalate. Two other schemes can end in a digit, but only after their semantic answer is itself taken: the type-side renames (1 and 2) and the property Value rename (4) escalate to the next free OfferInfo2 / ConfigValue2 rather than leave the collision unresolved. The method-side renames (5 and 6) have no numeric escalation — they produce one name and stop. When the pair is declared on a protocol, the protocol resolves first and conforming types adopt the names the protocol was emitted under — so an interface reference and a concrete reference agree even where the conformer declares its properties in the opposite order.
Two further member-side renames sit outside that table, in the name shaper rather than the de-collision pass, and both can apply on top of a name the table already produced:
-
Swiftsuffix — the member collides with something the generated C# class inherits rather than with a sibling. A generated class inheritsDispose(), so a Swiftdispose()binds asDisposeSwift(). -
Type-parameter collision — the member's name equals a type parameter of its declaring type, which C# forbids. It takes the same
Method/Withshapes as scheme 6, and is resolved on the final name, after anyAsyncsuffix.
Renames that a downstream binding needs are carried in the module database rather than recomputed by the consumer: class instance methods persist their full emitted identity, name and parameter types together, and renamed properties carry their own ledger entry. That is what keeps a cross-module reference agreeing with the name the producing module actually emitted.
Bindings generated from an Objective-C umbrella header follow the conventions an Apple-platform developer reads, rather than transcribing the C symbol:
-
Enum case prefixes are stripped, all-or-nothing across the case set. The enum's own type name is tried first (
MLNSourceKindTiler→Tiler); failing that, the module's acronym tag — inferred from the module's own extern constants, not guessed from a common prefix — is stripped at a token boundary (MLNMapTiler→MapTiler). If any case does not carry the prefix, the whole set keeps its original spelling. -
Delegate method names keep the semantics the first selector part carries. The receiver token is peeled off and the rest is kept, so
mapViewDidFailLoadingMap:withError:onMLNMapViewDelegatebinds asDidFailLoadingMapWithErrorrather than as its last keyword. Where the first part is only the receiver, it drops entirely —mapView:didSelectAnnotation:binds asDidSelectAnnotation. -
Types adopt the name Swift imports them under, where the framework's own Swift half references them —
FBSDKAccessTokenbinds asAccessToken, with the original name preserved for Objective-C runtime registration. Coverage here is partial by construction: the mapping is read out of the Swift ABI, which can only name a type its own members reference. A public Objective-C type that no Swift member mentions keeps its raw name, and a pure-Objective-C binding has no mapping to read at all. That has a consequence worth planning for — when an upstream release adds the first Swift reference to a previously unreferenced type, that type's C# name changes from the raw spelling to the Swift-import one. A rename that would collide is declined rather than disambiguated — never numbered. If the imported name is already taken by a declaration in the module, the rename simply does not happen and that type keeps its raw name. If two raw names import to the same Swift name, the raw names are sorted so the outcome follows the source rather than dictionary order: the first takes the imported name and the second keeps its raw one.
To find a member by its selector, search the generated ApiDefinition.cs for [Export("selector")] — the export always carries the original selector.
-
Argument order follows the Objective-C selector, not intuition. A validator declared
validationStateForExpirationYear:inMonth:binds asValidationState(string year, string month)— year first. Both parameters are strings, so a swapped call compiles and validates the wrong value. When a bound method's argument order reads oddly, check the[Export]selector before assuming a marshalling bug. -
A flattened Apple platform type is not a rename.
UIKit.UIView.ContentModesurfaces asUIViewContentModebecause that is the spelling Apple's own .NET bindings use. Nothing collided; the name is mapped through, not de-collided. -
A
Getprefix on a zero-argument method is a naming rule, not a hint about cost. It marks a noun-shaped method that would otherwise read as a property. - A trailing digit is usually the library's, not ours. Most digits in a bound name were transcribed from the Swift or Objective-C declaration. The generator does add one, but only where it has run out of meaning to use: the case-only rule above, the escalation on a type-side or property rename whose semantic name is itself already claimed, and — in an Objective-C binding — a final tie-break when two methods still clash after the name has been expanded to the full selector. It is never how a Swift overload gets its name.
- Supported Features — Full feature reference
- Known Limitations — What's not supported yet
- Getting Started — Set up your first binding
Swift Bindings for .NET
Get Started
Guides
- Upgrading
- Apple Frameworks
- SwiftUI Interop
- Customization
- Multi-Framework Libraries
- Publishing
- NativeAOT Deployment
Reference
Links