[swift-users] Constrained protocol extensions

Aleksandar Petrovic apetrovic at outlook.com
Wed Jun 8 15:44:08 CDT 2016


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

 		 	   		  


More information about the swift-users mailing list