Hacker News new | past | comments | ask | show | jobs | submit login
Type Variance in Swift (nomothetis.svbtle.com)
4 points by afthonos on July 15, 2014 | hide | past | favorite | 2 comments



In this example:

    func countFurballs(shelter:Shelter<Animal>) {
        println("Furballs: \(shelter.inhabitants.count)")
    }
    var catShelter = Shelter(inhabitants:[Cat()])
    countFurballs(catShelter) // throws compilation error
I believe that the countFurballs function could be made more generic:

    func countFurballs(shelter:Shelter<T>) {
        println("Furballs: \(shelter.inhabitants.count)")
    }
    var catShelter = Shelter(inhabitants:[Cat()])
    countFurballs(catShelter) // works?
I don't have Xcode in front of me, so that may still be a compiler error, but I believe it works.


Yes, it could be, but that doesn't change the variance of the container itself. For instance, if instead of counting, which was admittedly a bad example, I had wanted to feed the animals, that would not have worked.

(Sorry for the delay; I assumed nobody had read it… :-) )




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: