Skip to content

Ownership

Justin Wojciechowski edited this page Sep 5, 2026 · 10 revisions

Ownership and Disposal

Swift Bindings uses .NET's standard IDisposable pattern. If you're familiar with FileStream, HttpClient, or Xamarin's NSObject, you already know how ownership works.


For Most Users: Classes Just Work

Swift class instances are ARC-bridged — the GC finalizer calls swift_release automatically, just like Xamarin's ObjC binding finalizer calls release. You don't need to think about disposal for ordinary usage:

var pipeline = ImagePipeline.Shared;
var image = await pipeline.GetImageAsync(url);
imageView.Image = image.ToUIImage();
// GC handles cleanup — Swift deinit runs on finalization

Use Dispose() when you want deterministic cleanup of scarce resources (file handles, network connections, caches) — the same reason you'd use Dispose() on any .NET object:

using var handle = FileHandle.Create(path);
handle.Write(data);
// Deterministic close at scope exit — same pattern as FileStream

The SB1001 analyzer reports an Info-level diagnostic for undisposed Swift class locals — a gentle reminder, not a warning.

Writing through a struct property

A generated property that returns a Swift struct hands back a copy. Writing to a field of that copy — or calling a mutating method on it — updates the copy and discards it. Non-frozen structs project as classes, so the C# compiler has no reason to object:

config.Viewport.Width = 100;          // lost — hits a temporary
var viewport = config.Viewport;
viewport.Width = 100;
config.Viewport = viewport;           // the write reaches the original

The SB1003 analyzer reports a warning on this shape (assignment, +=, ++/--, mutating calls, indexers). It stays silent on protocol-typed receivers, where the write may be to your implementation. Full details, including the protocol false-negative, are in Known Limitations.

Equality and identity

A Swift class that does not conform to Equatable gets Equals/GetHashCode keyed on the live Swift handle: two C# wrappers that point at the same Swift instance compare equal, and a wrapper stays findable as a Dictionary/HashSet key even after it — or another wrapper for the same object — has been Disposed. That is reference identity (same underlying Swift object), not structural value equality. A class that does conform to Swift's Equatable instead gets value equality dispatched to Swift's == (and, when it also conforms to Hashable, a matching GetHashCode) — the same value semantics as the enum and struct projections described in Supported Features.

How to inspect the generated bindings for ownership rules

When you need to understand exactly what the generator decided for a particular type, look in the emitted .cs (usually under obj/.../swift-binding/ for SDK users):

# In the generated binding source
grep -n "class .* : ISwiftObject, IDisposable" MyLib.cs
grep -n "struct .* : ISwiftStruct" MyLib.cs
grep -n "SafeHandle\|SwiftClassHandle\|SwiftSafeHandle" MyLib.cs | head -20

Typical patterns you will see:

  • public partial class Foo : ISwiftObject, IDisposable → ARC class, SwiftClassHandle<Foo> under the hood.
  • public partial struct Bar : ISwiftStruct + no Dispose → pure frozen blittable struct (value copy, no cleanup).
  • public partial class Baz : IDisposable with an internal buffer + SwiftSafeHandle → frozen struct containing ref types (String, arrays, etc.).
  • public partial class Qux : ISwiftObject with no public Dispose (or Dispose is explicit) → the type is reference-counted but the generator decided users rarely need deterministic release.

Protocol proxies always implement IDisposable (they hold a GCHandle + the Swift witness table reference).


For Performance-Sensitive Code: SwiftDisposeScope

When creating many Swift objects in a loop or batch operation, use SwiftDisposeScope for efficient deterministic cleanup:

using (new SwiftDisposeScope())
{
    foreach (var url in urls)
    {
        var image = await pipeline.GetImageAsync(url);
        ProcessImage(image);
    }
    // ALL images disposed deterministically at scope exit
}

Objects created within a scope are automatically tracked and disposed in reverse order (LIFO) when the scope exits. No need to using each variable individually.

Escaping a scope

If you need an object to outlive its scope, detach it:

ImageResult result;
using (new SwiftDisposeScope())
{
    var img1 = pipeline.GetImage(url1);
    var img2 = pipeline.GetImage(url2);
    result = processor.Process(img1).DetachFromScope();  // Survives scope exit
    // img1, img2 disposed; result lives on
}

You can also move an object to the parent scope:

using (new SwiftDisposeScope())           // outer
{
    using (new SwiftDisposeScope())       // inner
    {
        var obj = CreateObject();
        obj.MoveToParentScope();          // Moves from inner → outer
    }
    // obj still alive — disposed when outer scope exits
}

For Struct Bindings Projected as Classes

Some Swift structs are projected as C# classes rather than structs — specifically non-frozen structs and frozen structs with reference fields (e.g., String properties). Like Swift class bindings, the GC finalizer handles cleanup automatically — disposal is optional:

// Works fine — GC finalizer runs VWT Destroy automatically
var config = ImagePipeline.Configuration();
config.MaxConcurrentDownloads = 4;

// Also fine — deterministic cleanup at scope exit
using var config2 = ImagePipeline.Configuration();
config2.MaxConcurrentDownloads = 4;

Use using when you want deterministic cleanup of scarce resources — the same reason you'd use using on a FileStream.

The SB1001 analyzer reports an Info-level diagnostic for undisposed struct locals — a gentle reminder, not a warning.

Frozen blittable structs (projected as C# struct) need no disposal at all — they're pure value types with empty Dispose() bodies.

How to tell which type you have

Swift Type C# Projection Implements Disposal
class class ISwiftObject Optional (GC handles it)
struct (non-frozen) class ISwiftStruct Optional (GC handles it)
struct (frozen, has reference fields) class ISwiftStruct Optional (GC handles it)
struct (frozen, all value fields) struct ISwiftObject Not needed
enum class ISwiftObject Optional (GC handles it; singleton cases skip disposal)
Protocol existential (any P, any A & B) class (protocol proxy) ISwiftObject Recommended (holds native witness tables; an owned return adopts the container's +1)
any Error Swift.Foundation.AnyError (class) ISwiftObject Recommended (owns the boxed error's +1; (any Error)? → AnyError?, a nullable reference)

Delegates in weak Swift properties

Nearly every Apple delegate property is declared weak; a few are unowned or unowned(unsafe). That annotation means the Swift side takes no reference on what you assign — your application is the only owner. Assign a C# implementation and keep no reference of your own, and the garbage collector is entitled to collect it. The Swift slot then reads back as nil and callbacks stop arriving.

So the field, not the assignment, is the ownership:

public sealed class ScannerPage : UIViewController
{
    MyScannerDelegate _delegate;                // this field is what keeps it alive

    void Attach(Scanner scanner)
    {
        _delegate = new MyScannerDelegate();
        scanner.Delegate = _delegate;           // weak on the Swift side — nothing here holds it
    }
}

A local would not be enough. Hold the implementation on the owning view controller, view model, or service for as long as the Swift side may call it. Generated properties on this path carry a <remarks> note saying so.

Dropping your reference is a legitimate thing to do — it is what weak is for, and the slot clearing is the documented behaviour. What it is not is a way to stop callbacks that are already in flight.

When Swift calls anyway

A framework that takes a delegate through a weak property often also holds it somewhere else for the duration of a piece of work: an internal observer array, a closure captured by a queued block, an operation already running. Through that other reference, Swift keeps calling the conformance after your own reference is gone. A callback can also simply race a drop on another thread.

Before 0.19.4 a callback arriving in that state stopped the process. It now degrades, following what Swift itself does with a nil weak delegate:

The requirement returns The degraded call gives Swift
Void nothing — the call is dropped
An optional nil
Bool false
An integer or floating-point type 0
String ""
Array, Set, Dictionary the empty collection
A frozen value type made only of integers, floating-point values and booleans, at any nesting depth its zeroed value
An optional closure nil
A non-optional closure a closure of the requirement's own type that does nothing when called
async throws a thrown error your await observes

The element type of a collection is not part of this: an empty [any P] needs no element, so it is synthesized like any other empty array.

Delegates assigned into ordinary strong Swift properties are unaffected. Swift holds those for as long as it holds the conformance, so a missing implementation there still means something has gone wrong internally, and is still reported loudly.

Finding out that it happened

A degraded callback is quiet by construction, which makes "my delegate stopped firing" hard to explain. So the first time a given conformance degrades, the runtime writes a line through System.Diagnostics.Trace and raises ProxyDegradation.ImplCollected. Later callbacks on the same conformance stay silent, so a per-frame delegate cannot fill a log.

Swift.Runtime.ProxyDegradation.ImplCollected += (_, e) =>
    Console.WriteLine($"Swift called {e.Member} on a collected implementation (0x{e.Handle:X})");

Handlers run on whichever thread Swift called in on — including a Swift-owned queue — so marshal to the UI thread yourself if you touch UI, and do not throw: the callback is mid-way across a native boundary, so an exception from a handler is caught and dropped rather than propagated.

ProxyDegradation.ReportCount gives the number of conformances that have reported so far, which is convenient to assert on in a test.

Two shapes that still stop

A synchronous throws requirement cannot report the error. Its reverse-dispatch entry point returns a value and carries no error slot, so a degraded synchronous throws call comes back as the identity value for its return type, exactly like a non-throwing one. Only async throws requirements, which resume a continuation, have somewhere to put a failure.

Some return types have no value to synthesize. A non-optional class or existential has no null to give. An enumeration's zeroed form is a real case, but a specific one your code never chose, and silently returning it would be worse than saying so. A non-optional Swift pointer (UnsafePointer, UnsafeMutablePointer, UnsafeRawPointer, OpaquePointer) excludes the null address from its values, so Swift is entitled to dereference whatever comes back — and a frozen struct carrying such a pointer, or a class reference, in any of its fields is refused for the same reason. A resilient (non-frozen) struct such as Foundation.URL gives no assurance that zeroed bytes are a valid instance.

For those, a degraded callback still stops the process, with a message naming the member, the conformance, and the fix.

The remedy

Degradation keeps a lifetime mistake from taking the process down; it does not make the callbacks arrive. If you want them to keep arriving, hold a reference to the implementation for as long as the Swift side may call it. Assigning into a weak Swift property and keeping no reference of your own is asking for the object to be collected.


Summary

Scenario What to do
Swift class or struct binding, normal usage Nothing — GC handles it
Scarce resources (file handles, caches) using or Dispose() for deterministic cleanup
Many Swift objects in a loop SwiftDisposeScope
Frozen blittable struct Nothing needed
A C# delegate assigned to a weak/unowned Swift property Hold it in a field for as long as Swift may call

Advanced: The 11 Boundary Ownership Rules

For binding authors and contributors working on the generator or runtime, the full ownership rules are documented below. These govern every generated P/Invoke boundary. Application developers do not need to know these.

1. Class inputs are always borrowed

When C# passes a class instance to Swift, the wrapper uses takeUnretainedValue() — never takeRetainedValue(). The caller retains ownership. Swift borrows the reference for the duration of the call.

2. Class outputs are always owned

When Swift returns a class instance to C#, the wrapper uses passRetained().toOpaque(). C# receives exactly one ownership unit. SwiftClassHandle<T> manages this via ARC-bridged Arc.Release in its finalizer.

3. Non-C-representable returns use explicit result buffers

Types that can't be returned directly through the C calling convention (structs with non-trivial layout, enums with payloads, existential containers) are returned via a caller-allocated buffer passed as an UnsafeMutableRawPointer parameter.

4. Every heap allocation in generated Swift must have one clear consumer/free site

Generated wrapper code that allocates heap memory (closure context buffers, enum payload buffers) must have exactly one consumer that frees the allocation.

5. Every explicit retain on C# side must have one terminal release path

If C# code calls Arc.Retain(), there must be exactly one release that fires on every possible exit path — success, error, and cancellation.

6. VWT Destroy is for structs/enums only

Struct and enum disposal calls the Value Witness Table (VWT) Destroy function to run Swift's deinitializer (deinitialize(count: 1)). On the explicit dispose path (user thread), VWT Destroy is called directly via the type's cached metadata. On the finalizer path (GC thread), a CallConvCdecl trampoline in the SwiftBindings.Runtime native helper (the signed SwiftBindingsRuntime.xcframework) handles the call — avoiding JIT compilation on the finalizer thread. The .NET side separately frees the outer managed buffer. Classes don't need VWT Destroy — SwiftClassHandle<T> calls Arc.Release directly via its SafeHandle finalizer.

7. Async handoff must extend liveness beyond the P/Invoke frame

When an async P/Invoke hands off a reference to a Swift async continuation, the reference must remain alive until the continuation completes.

8. Optional reference = nullable-pointer ABI; optional value type = buffer ABI

Optional<ClassType> is represented as a nullable IntPtr (null = .none). Optional<StructType> or Optional<EnumType> uses a buffer with a tag byte.

9. Wrapper-library routing is all-or-nothing per member

A given method routes through exactly one mechanism: @_cdecl wrapper (CallingConvention.Cdecl), native thunk (CallingConvention.Cdecl, ARM64 or SysV AMD64), or direct P/Invoke (CallConvSwift).

10. Proxy/existential bridge objects must be explicitly disposable and idempotent

C#-implemented protocol proxies and existential bridge objects hold native resources (witness tables, existential containers). They implement IDisposable and must tolerate multiple Dispose() calls.

11. Owned existential and wire-carrier returns adopt and release the payload's +1

A Swift function returning an existential (any P, any A & B, or any Error) or a wire-carrier copy-out collection (Array, Dictionary, Set, Optional, Result) transfers its payload at +1. The generated wrapper adopts that retain and releases it exactly once: existential proxies and Swift.Foundation.AnyError release on Dispose/finalize — a value-witness Destroy through the container's own metadata, or swift_errorRelease for the single boxed reference behind any Error — and collection elements are copied into self-owning C# values as they are marshalled out, so each escapes the wire buffer owning its own retain. Borrowed existential parameters — receiver-callback arguments that live only for the duration of the call — stay non-owning, so the C# side never over-releases a value it does not own.


Practical Notes for Application Developers

Retain cycles

The generator cannot break Swift retain cycles for you. If your Swift library has a classic delegate or parent/child cycle — or you hand Swift a C# callback that captures the very object the callback is attached to — you are responsible for the same weak-reference or explicit cleanup patterns you would use in pure Swift. Three tools help:

  • SB1002 analyzer — warns at build time when a callback you pass to a Swift-backed object captures that same object — the shape that, if the object stores the callback, creates an unbreakable cross-heap retain cycle (the managed delegate roots the Swift object and the Swift object roots the delegate). The analyzer can't tell a stored callback from one invoked synchronously, so treat it as guidance toward WeakSwiftReference<T>, not proof of a leak.
  • WeakSwiftReference<T> (in Swift.Runtime) — capture a WeakSwiftReference<T> and reach the object through .Target / .TryGetTarget(out var obj) inside the callback instead of capturing it directly, breaking the C#-side leg of the cycle. T is constrained to a reference type, since only heap-backed Swift classes can participate in a cycle.
  • SwiftLeakCensus (in Swift.Runtime) — a DEBUG diagnostic. Call SwiftLeakCensus.Report() before and after a scope you expect to fully release and compare the RegisteredProxies / StronglyHeldProxies / ProxyImplRoots counts. A self-capturing cycle is unbreakable from the runtime side, so this frees nothing — it makes the leak visible as counts that fail to return to baseline.

@MainActor isolation

A binding whose Swift counterpart is @MainActor-isolated carries a [SwiftMainActor] attribute. It's informational — .NET has no actor-isolation model — but in DEBUG builds the generated wrapper asserts it's invoked on the platform main thread, so an off-main-thread call is caught during development; in Release it's a no-op. Calling such an API off the main thread is unsupported in Swift, so keep those calls on the main thread.

Process exit / finalizer thread

On normal process exit the .NET finalizer thread may be suppressed. SwiftExitGuard (inside the runtime) detects this and skips the expensive VWT Destroy / Arc.Release calls that would otherwise run during shutdown. This is why you sometimes see "leaked" objects in crash dumps from dotnet test or unit test runners — they are not real leaks in a long-running app.

ISwiftStruct vs SwiftSafeHandle

If the generated C# type is a class that implements ISwiftStruct and contains an internal SwiftSafeHandle or raw buffer, it came from a frozen struct that contained reference-type fields. The disposal path runs the VWT Destroy on the buffer contents. Pure value structs are projected as C# struct and have no-op Dispose().

These three distinctions (class vs struct projection, SafeHandle vs raw buffer, VWT Destroy vs Arc.Release) cover 95% of the "why is this thing not being freed when I expect?" questions.

Clone this wiki locally