Hi swift-users,
I'm trying achieve something similar to C++ template specialization with
protocol extensions, and I found a strange behavior:
// ----------
protocol Printer {
associatedtype TestType
var value: TestType { get }
func printMe()
}
extension Printer {
func printMe() {
print("Base printer: \(value)")
}
}
extension Printer where TestType: SignedIntegerType {
func printMe() {
print("Int printer: \(value)")
}
}
func testPrint<T>(value: T) {
print("testPrint")
}
func testPrint<T where T:SignedIntegerType>(value: T) {
print("testPrint for int")
}
class PrintClass<T>: Printer {
var value: T
init(value: T) { self.value = value }
}
func printPrinter<T>(printer: PrintClass<T>) {
printer.printMe()
testPrint(printer.value)
}
let intPrinter = PrintClass(value: 42)
let stringPrinter = PrintClass(value: "test value")
intPrinter.printMe() // Int printer: 42
stringPrinter.printMe() // Base printer: test value
testPrint(intPrinter.value) // testPrint for int
testPrint(stringPrinter.value) // testPrint
printPrinter(intPrinter) // Base printer: 42 (!!!)
// testPrint
(!!!)
// ----------
The compiler correctly chooses specialized protocol extension as long as the
function call is in the same scope with the object declaration. But all
knowledge about types seems to be lost in the last line, when the scope is
changed, in function printPrinter().
Is this a bug or desired behaviour?
Alex
_______________________________________________
swift-users mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-users