After talking with some people who were trying to use Noncopyable existentials for various purposes, I set out about a month ago to see what was possible here. I have since implemented an experimental feature "NoncopyableCasting" that enables many kinds of common operations involving noncopyables. I'm still exploring what's feasible, but here's a partial list of what you can do now with this feature:
type(of:)borrows its argument instead of consuming.- Most forms of
isborrow the subject instead of consuming. if let,guard let,while let,if case, and consumingswitchgenerally work for noncopyable types. In all of these, a failing cast leaves the original available, so you can chainif letor use the original value in anelseordefault:clause.
There are some limitations to the above. I'm not certain I'll be able to address all of these, at least not in the short term:
- New runtime support is required for some of these cases, especially the
ishandling and some switch constructs that are based on it. So some cases may not back-deploy on ABI-stable platforms until the runtime support can be back-deployed. - Borrowing
switchis complicated. In essence, Swift's casting allows you to do things like create or project out of existentials or optionals, and those are hard to do without destroying the original. Borrowed function arguments have the same challenge. - Optional noncopyable existentials (e.g.
case x as (any P & ~Copyable)?:) are also proving troublesome. - There are a number of other edge cases that I hope to clean up, many involving interactions with closures and general noncopyable support.
Some of these limitations I might be able to lift, others will get left as diagnostics suggesting workarounds.
I hope to put together a proper proposal in the next couple of weeks with more details about all of this.
Cheers,
Tim