问题
I am trying to write a function to sum an array of numeric types. This is as far as I got:
protocol Numeric { }
extension Float: Numeric {}
extension Double: Numeric {}
extension Int: Numeric {}
func sum<T: Numeric >(array:Array<T>) -> T{
var acc = 0.0
for t:T in array{
acc = acc + t
}
return acc
}
But I don't know how to define the behaviour of the +
operator in the Numeric
protocol.
回答1:
protocol Numeric {
func +(lhs: Self, rhs: Self) -> Self
}
should be enough.
Source: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/
回答2:
I did it like this but I was just trying to add two values and not using array but thought this might help.
func addTwoValues<T:Numeric>(a: T, b: T) -> T {
return a + b
}
print("addTwoValuesInts = \(addTwoValues(a: 3, b: 4))")
print("addTwoValuesDoubles = \(addTwoValues(a: 3.5, b: 4.5))")
回答3:
Since Swift 5, there is a built in AdditiveArithmetic protocol which you can constrain to:
func sum<T: AdditiveArithmetic >(array:Array<T>) -> T{
var acc = T.zero
for t in array{
acc = acc + t
}
return acc
}
Now you don't need to manually conform the built-in types to a protocol :)
来源:https://stackoverflow.com/questions/30046669/how-do-i-add-two-generic-values-in-swift