Skip to content

Instantly share code, notes, and snippets.

@bklimt
Created June 4, 2014 02:50
Show Gist options
  • Save bklimt/08c7d3b7b0ffc08e1976 to your computer and use it in GitHub Desktop.
Save bklimt/08c7d3b7b0ffc08e1976 to your computer and use it in GitHub Desktop.
Testing covariance in Swift
class Fruit {
var name = "Fruit"
var description : String {
return name
}
}
class Apple : Fruit {
init() {
super.init()
self.name = "Apple"
}
}
func printFruit(fruits: Fruit[]) -> String[] {
return fruits.map() { (fruit : Fruit) -> String in
return fruit.description
}
}
let apple1 = Apple()
apple1.description
let apple2 = Apple()
apple2.description
let apples : Apple[] = [apple1, apple2]
// Apple[] is a subtype of Fruit[]
printFruit(apples)
class Banana : Fruit {
init() {
super.init()
self.name = "Banana"
}
}
func mangleFruit(fruits: Fruit[]) -> String[] {
fruits[0] = Banana()
return printFruit(fruits)
}
// Oops, the type system allows this broken code
mangleFruit(apples)
@O1O1O1O
Copy link

O1O1O1O commented Jun 4, 2014

Thanks for doing this - I couldn't figure out from the docs what would actually happen and don't use a Mac to try it.

So now the $64,000 question - is the final "Oops" comment your expectation, or what actually happened?

@ljw1004
Copy link

ljw1004 commented Jul 20, 2014

This test is flawed. Arrays have value semantics. When you invoke mangleFruit(apples), the function isn't getting a reference to the existing array; it's getting a NEW array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment