[swift-evolution] Covariance and Contravariance

Simon Pilkington simonmpilkington at icloud.com
Wed Dec 9 01:47:36 CST 2015


Hi,

Is providing Covariance and Contravariance[1] of generics going to be part of the work on generics for Swift 3? I am sure this topic has come up within the core team and I was wondering what their opinion on the topic was.

I can see this as beneficial as it would allow the compiler - in conjunction with type inference - to retain more type information and hence allow code be more type safe. For example -

class ConcreteClass<GenType : GenericType> {
    ...
    
    func getFunction() -> GenType {
        ...
    }
    
    func putFunction(input: GenType) -> Bool {
        return ...
    }
    
}

protocol GenericType {
    ...
}

class GenericType1 : GenericType {
    ...
}

class GenericType2 : GenericType {
    ...
}

let array = [ConcreteClass<GenericType2>(...), ConcreteClass<GenericType1>(...)]

let x : GenericType = array[0].getFunction() // this would compile as array would be of type ConcreteClass<types that extend GenericType>
                      // currently array is of type AnyObject so this line doesn’t compile
array[0].putFunction(…) // this would still not compile as it would break type guarantees

As a downside I can see it as making generics more complex and difficult to understand. On balance I think probably the benefit in improved type safety is worth it but I was interested in what others thought.

Cheers,
Simon

[1] https://dzone.com/articles/covariance-and-contravariance
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/13b77300/attachment.html>


More information about the swift-evolution mailing list