Swift: Generic factory method creates wrong instance type
| Originator: | johanvase | ||
| Number: | rdar://19426183 | Date Originated: | 09-01-2015 |
| Status: | Open | Resolved: | |
| Product: | iOS | Product Version: | Xcode 6.1.1 |
| Classification: | Other bug | Reproducible: | Always |
Summary:
A factory method that should create an instance of a generic type creates the wrong instance. It seems related to which type constraint that is set since setting the constraint to "NSObject" instead of "Vehicle" makes the correct instance type.
Steps to Reproduce:
Insert this sample code in Playground:
import Foundation
class Vehicle {
func getType() -> String {
return "vehicle"
}
}
class Bicycle: Vehicle{
override func getType() -> String {
return "bicycle"
}
}
func construct<T : Vehicle>() -> T { //NB: Change constraint to NSObject (and let vehicle subclass NSObject), and it all works
return T()
}
let a : Bicycle = construct()
println ("\(a.getType())") //Expected "Bicycle". Got "Vehicle"
Expected Results:
I expected a Bicycle object to be created since that is the generic type (can be verified by printing out the type in the "construct" function
Actual Results:
A Vehicle object was created
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!