Created
June 4, 2014 02:50
-
-
Save bklimt/08c7d3b7b0ffc08e1976 to your computer and use it in GitHub Desktop.
Testing covariance in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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