Hello everyone,
I'm interested in dispatching via type resolution in overloaded functions, but I'm not sure how to implement this paradigm correctly. Currently, I have naive straightforward version, which doesn't work:
protocol Custom {}
extension Float: Custom {}
extension Int: Custom {}
func compute(_ x: Int, _ y: Int) -> Int {
print("Result 0: \(x - y)")
}
func compute(_ x: Float, _ y: Float) -> Int {
print("Result 1: \(x + y)")
}
func compute(_ x: Int, _ y: Float) {
print("Result 2: \(Float(x) - y)")
}
func schedule<T: Custom, U: Custom>(x: T, y: U) {
print("x=\(x) has type \(type(of: x))")
print("y=\(y) has type \(type(of: y))")
compute(x, y)
}
I'm getting this error, which is slightly confusing, as I have already extended Int and Float types with Custom protocol. Theoretically, the compiler should pick up this information and allow to 'custom' variables to be passed to the overloaded compute
function.
error: repl.swift:21:3: error: cannot invoke 'compute' with an argument list of type '(T, U)'
compute(x, y)
^
repl.swift:21:3: note: overloads for 'compute' exist with these partially matching parameter lists: (Int, Int), (Float, Float), (Int, Float)
compute(x, y)
^
Any help is appreciated
Swift version:
$ swift --version
Apple Swift version 4.2.1 (swiftlang-1000.0.42 clang-1000.10.45.1)
Target: x86_64-apple-darwin18.2.0