Swift: contravariant generic types
| Originator: | ide | ||
| Number: | rdar://17193459 | Date Originated: | 05-Jun-2014 |
| Status: | Open (duplicate of 17318803) | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 6 b1 |
| Classification: | Feature | Reproducible: | N/A |
Summary:
There is no way in Swift to express "a class whose generic parameter type is a supertype of a specified type". That is, something like "MyGenericClass<MySubtype : T>", where MySubtype is a concrete type and T is a generic supertype.
This is important when defining generic, custom data structures and writing to them. In the example below, the custom data structure is an animal Pen. It is safe to add a Cat to either a Pen<Animal> or Pen<Cat>, but there is no way to express "Pen<T where T is a supertype of Cat>"
Steps to Reproduce:
Run this program:
class Animal {}
class Cat : Animal {}
class Pen<T> {
var animals: T[]
init() {
animals = T[]()
}
func addAnimal(animal: T) {
animals.append(animal)
}
func allAnimals() -> T[] {
return animals
}
}
func herdCat<Cat : T>(cats: Pen<T>) { // error; potential syntax
cats.addAnimal(Cat())
}
var cats = Pen<Cat>()
herdCat(cats)
Expected Results:
The program should compile (perhaps with different syntax).
Actual Results:
The program does not compile because "<Cat : T>" is not valid.
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!