Swift lacks covariance

Originator:k
Number:rdar://23608799 Date Originated:19-Nov-2015 09:24 AM
Status:Duplicate Resolved:
Product:iOS SDK Product Version:Swift 2.1
Classification:Enhancement Reproducible:Always
 
Summary:
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 types.

For example, I expect that this class can behave covariantly.  (Note that it does not compile the current compiler:

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.

There's another example here:

http://stackoverflow.com/questions/33752968/swift-cast-generic-type-into-same-generic-type-but-with-a-subclass-of-associate/33759858#33759858

Steps to Reproduce:
See description

Expected Results:
See description

Actual Results:
See description

Version:
Swift 2.1

Notes:


Configuration:
Any

Attachments:

Comments

To jlieske

Thanks for the description!

https://openradar.appspot.com/17226586


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!