Swift lacks covariance and contravariance

Originator:jlieske
Number:rdar://17226586 Date Originated:08-Jun-2014 07:20 PM
Status:Duplicate Resolved:
Product:OS X SDK Product Version:Xcode6 beta: Version 6.0 (6A215l)
Classification:Enhancement Reproducible:Always
 
The Swift language supports supports strong typing, but there is a gap when using generic types in hierarchies: there is no mechanism to define covariant and contravariant types.

For example, I expect that this class can behave covariantly.  (Note that it does not compile the current compiler; I have opened rdar://17226390 for that issue.)

class Cons<T> {
    let head: T
    let tail: Cons<T>?
    init(head: T, tail: Cons<T>? = nil) {
        self.head = head
        self.tail = tail
    }
}

Using the type hierarchy from the Swift manual:

class MediaItem {
    let name: String
    init(name: String) {
        self.name = name
    }
}

class Movie: MediaItem {
    let director: String
    init(name: String, director: String) {
        self.director = director
        super.init(name: name)
    }
}

class Song: MediaItem {
    let artist: String
    init(name: String, artist: String) {
        self.artist = artist
        super.init(name: name)
    }
}

I should be able to construct a value of type Cons<MediaItem> from a Cons<Song> — that is, use Cons in a covariant fashion:

let m1 = Movie(name: "Casablanca", director: "Michael Curtiz")
let m2 = Movie(name: "Citizen Kane", director: "Orson Welles")

let s1 = Song(name: "Blue Suede Shoes", artist: "Elvis Presley")
let s2 = Song(name: "The One And Only", artist: "Chesney Hawkes")
let s3 = Song(name: "Never Gonna Give You Up", artist: "Rick Astley")

let movies = Cons(m1, Cons(m2))
let songs = Cons(s1, Cons(s2, Cons (s3)))

let mediaItems = Cons<MediaItem>(m1, Cons<Songs>(s1, Cons(s2)))

However, this seems to be incompatible with the current Swift language spec.

Comments

Duplicate of 17318803 (Open)


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!