Given the following code:
struct Foo<T> {
let value: T
}
let bar: Foo<Any> = Foo<Bool>(value: true) // ERROR
I get the following error:
Cannot convert value of type 'Foo' to specified type 'Foo'
With a slight adjustment to this code:
struct Foo<T> {
let value: T
}
let bar = Foo<Any>(value: true)
print(bar as? Foo<Bool>) // WARNING
I get this warning:
Cast from 'Foo' to unrelated type 'Foo' always fails
Why do I get this error? These two types seem to be related to each other considering the type of Bool
can, in fact, be converted to Any
as shown in the following example:
let bar: Any = Bool(true)
While this example could be solved by removing out the specified type,
let bar = Foo<Bool>(value: true)
let bar: Foo<Any> = Foo(value: true)
This does not give me the results I want as either Foo.value
or bar
are the wrong type.
Given a more complex situation where the type must be explicitly specified this solution does not work. Could anyone help explain why this is happening and provide a solution?