Converting NonCopyable types to any Protocol

Consider the following code:

public protocol P: ~Copyable {}
struct A: P, ~Copyable {}

let a = A()
let p = a as any P

This gives the following error:

/private/tmp/test-noncopy/Sources/main.swift:6:9: error: cannot convert value of type 'A' to type 'any P' in coercion
4 |
5 | let a = A()
6 | let p = a as any P
  |         `- error: cannot convert value of type 'A' to type 'any P' in coercion

Is there any way to convert A to any P?

1 Like

Not to any P, because protocol P: ~Copyable means that types conforming to P may or not be Copyable.

It does work if you use any P & ~Copyable, though:

public protocol P: ~Copyable {}
struct A: P, ~Copyable {}

// Wrapper function to make `a` not global.
// Because global variables can't be consumed.
func f() {
    let a = A()
    let p = a as any P & ~Copyable // works
}
2 Likes

You can write let p = a as Any P & ~Copyable. But note a is consumed for this.

1 Like

Thanks @ole and @CrystDragon. Should have thought of that, that makes sense!

1 Like