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) |
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
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?