You may have a similar need for other functions, and their implementation for all types with integer and floating point (or other "summed" things) will lead to massive duplication of code.
One partial solution, specifically for +, -, *, /,%, should require IntegerArithmeticType protocol compliance:
func example<T: IntegerArithmeticType>(x: T, y: T) -> T { return x + y } println(example(40, 2))
This does not apply to floating point types because they do not implement the overflow operations defined in the _IntegerArithmeticType protocol, which inherits IntegerArithmeticType.
However, type extensions for the specific consistent functionality of the operator function are not "annoying" as you think:
protocol Summable { func +(lhs: Self, rhs: Self) -> Self } extension Int: Summable {} extension Double: Summable {} extension String: Summable {}
You do this once, then you can use Summable in your code forever:
func example<T: Summable>(x: T, y: T) -> T { return x + y } println( example("4", "2") )
In fact, and as @connor pointed out, this is equivalent to what you mentioned in response to @ Jean-PhilippePellet.
milos
source share