Inconsistent generics behavior

Given the following code snippet:

class Container<Value> {
    let contained: Value
    
    init(_ contained: Value) {
        self.contained = contained
    }
}

let containerString = Container("str")
let anyStringContainer: Any = containerString
if let anyContainer = anyStringContainer as? Container<Any> {
    print(anyContainer)
} else {
    print("No")
}

print("-")
    
let arrayStrings = ["str"]
let anyArrayStrings: Any = arrayStrings
if let anyArray = anyArrayStrings as? Array<Any> {
    print(anyArray)
} else {
    print("No")
}

You will receive the following output:

No
-
["str"]

My question is why array can cast element to Any, but my custom container can't? Is there a way to achieve similar behavior for custom container?

Xcode Version 13.1 (13A1030d)

1 Like

Array has "magic" behavior built into the language to enable this. Custom types cannot express this behavior in Swift itself. You could write an explicit initializer for Container<Any> that takes a Container<T> as an argument, but that's about it.

4 Likes

Sad :frowning:
But thanks :slight_smile: