protocol Shape {}
class Rect: Shape {}
class Square: Rect {}
struct Box<T: Shape> {
let shape: T
}
let box1 = Box(shape: Square())
let box2: Box<Rect> = box1
// Error: Cannot assign value of type 'Box<Square>' to type 'Box<Rect>'
let box3: Box<Rect> = Box(shape: Square())
// However, this does compile
Since generic types are invariant, I expected this to be an compile error, as Box<Rect> and Box<Square> are distinct types. However, the code does compile.
Why does Swift allow Box(shape: Square()) to be assigned to Box<Rect> here?
Invariance means that a Box<Square> isn't a Box<Rect>. And if you were constructing a Box<Square> and assigning it to your Box<Rect> variable, that wouldn't compile. But that's not what you're doing.
A Square is still a Rect. A Box<Rect> is constructed with a single Rect, and a Square is a Rect, so a Square can be the Rect used to construct a Box<Rect>. What you're doing is constructing a Box<Rect> with your Square, and assigning it to your Box<Rect> variable. That's all fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With