WritableKeyPath and ~Copyable

I am trying to use a ReferenceWritableKeyPath to a non-copyable value.
The compiler does not allow it. I produced this minimal example:

enum Link : ~Copyable {
case last
}

public protocol Linkage {
        associatedtype Element : AnyObject
        static var link: ReferenceWritableKeyPath<Element, Link> { get }
}

The compiler surprised me by complaining:

ncwkp.swift:7:19: error: type 'Link' does not conform to protocol
'Copyable'
 5 | public protocol Linkage {
 6 | 	associatedtype Element : AnyObject
 7 | 	static var link: ReferenceWritableKeyPath<Element, Link> { get }
   >                   `- error: type 'Link' does not conform to
protocol 'Copyable'
 8 | }
 9 | 

The only thing I can think of is that the KeyPath family of types may
need to encompass borrowing/consuming semantics before a keypath to a
noncopyable value can work.

David

Correct. SE-0437: Noncopyable Standard Library Primitives acknowledges that key paths are one of the areas in the standard library that needs more work to make it compatible with non-copyable types:

Additional future work

Fully supporting ownership control and noncopyable types will require overhauling much of the existing Standard Library.

This includes generalizing dynamic runtime operations -- a huge area that includes facilities such as isa checks, downcasts, existentials, reflection, key paths, etc. (For instance, updating print() to fully support printing noncopyable types is likely to require many of these dynamic features to work.)

[…]

Many of these depend on future language enhancements, and as such they will be developed alongside those.

4 Likes