sam-sduo
(Srinath2763 Sduo)
1
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'
Ray_Fix
(Ray Fix)
2
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).