Cannot convert value of type 'Container<View2>' to expected argument type 'Container<UIView>'

public class Container<U: UIView>: NSObject {
    public var subContainer: [Container] = []
    
    override public init() {
        super.init()
    }
}

public class VideoContainer: Container<UIView1> {
    var titleContainer = TitleContainer()
    
    override init() {
        super.init()
        self.subContainer.append(titleContainer)
    }
}

public class TitleContainer: Container<UIView2> {
    override init() {
        super.init()
    }
}

public class UIView1: UIView {
    
}

public class UIView2: UIView {
    
}

To resolve the Swift type error, use type erasure or a base class for subContainer to accept different Container types. Ensure downcasting is handled when accessing elements.

Regards,
the Disney HUB on the go

Sorry, I don't quite understand. Could you please give me a specific example?

Your are using generics that bound your container to specific types, but then try to store in the array two different types.

In VideoContainer array expects to have instances of itself or other types that can be thought as Container<UIView1>, and TitleContainer is totally different, as its base type actually Container<UIView2>.

You can introduce protocol that can be set as array type to something like any ContainerType, for example. And confirm Container to it. Then you’ll be able to store any type of container there, but type information about view from generic parameter will be lost.