Non-copyable associatedtype for non-escapable variables in public APIs

the associated type issue is, IIUC, a yet-to-be-implemented feature – the pitch to add support for it is here: Pitch: Suppressed Default Conformances on Associated Types.

ideally i think you'd use an ~Escapable type since that's the tool being designed to support these use cases (~Copyable does enforce nonescaping use in many instances, but in general the concepts are distinct). but per my understanding, such types still require use of the -enable-experimental-feature Lifetimes flag so that lifetime dependencies can be recorded and enforced. without that feature, it seems you can't even initialize such types in many (all?) cases. if you have a tolerance for that, you could try turning it on and using a non-escapable wrapper to vend to your closure. i was playing with that here, but i'm not sure it does quite what you want.

if you can't get the static checking to work, you could potentially try runtime enforcement. you'd pass a reference type wrapper to your clients, and then when the closure has run, perform the isKnownUniquelyReferenced check on it to infer whether it escaped.

1 Like