I donβt think you can imitate the Java pattern, but you might not need it. You can simply use ChildClass wherever the code expects a ParentClass . So using your example:
class TestGenerics { var dict: Dictionary<String, GenericClass<ParentClass>> = [:] func test() { var derivedClassInstance = GenericClass<ParentClass>() dict.updateValue(derivedClassInstance, forKey: "name") } }
Now just use ChildClass to populate foo
let test = TestGenerics() test.test() test.dict["name"]?.foo = ChildClass()
This code compiles without errors. However, Swift does not support covariance in custom generic classes, so you cannot change the dictionary using the covariant type, so the following does not compile:
test.dict = Dictionary<String, GenericClass<ChildClass>>() //Error: 'ChildClass' is not identical to 'ParentClass'
This is not very intuitive, since covariance is really supported on the native array and dictionaries, so this is allowed:
let array: Array<ParentClass> = Array<ChildClass>() let dic: Dictionary<String, ParentClass> = Dictionary<String, ChildClass>()
But not this:
let generic: GenericClass<ParentClass> = GenericClass<ChildClass>() //Error: 'ChildClass' is not identical to 'ParentClass'
Basically, Swift considers Array<ChildClass> be a subtype of Array<ParentClass> , but at the moment it is not possible to tell the compiler that GenericClass<ChildClass> is (or should be) a subtype of GenericClass<ParentClass> . Hopefully as the language develops, a way will be added to declare custom classes as covariant.