Runtime assignment of a concrete implementation to an optional opaque protocol type fails during compilation

In the following example I get a compile error for the variable deferredAssignment at compile time:

Cannot assign value of type 'GenericClass' to type 'some Generic'

whereas inline assignment succeeds. Am I missing something?

protocol Generic {

func getSelf() -> Self


class GenericClass: Generic {

func getSelf() -> Self {  return self }


class GenericChildClass: GenericClass {

override func getSelf() -> Self {  return self }


var inlineAssignment: (some Generic)? = GenericClass() // This compiles fine

var deferredAssignment: (some Generic)?

deferredAssignment = GenericClass() //Cannot assign value of type 'GenericClass' to type 'some Generic'

If you remove the deferred assignment compiler error and try to build you get this failure:

error: underlying type for opaque result type '(some Generic)?' could not be inferred from return expression

I think that because the generic type needs to be known at compile time. The inline assignment succeeds since the compiler can use type inference to lock in the exact type.

If you want something that is dynamic and can be swapped out at runtime, you need (any Generic).