[英]How do I add two generic values in Swift?
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.但我不知道如何定义
Numeric
协议中+
运算符的行为。
protocol Numeric {
func +(lhs: Self, rhs: Self) -> Self
}
should be enough.应该够了。
Source: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/来源: http : //natecook.com/blog/2014/08/generic-functions-for-incompatible-types/
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))")
Since Swift 5, there is a built in AdditiveArithmetic
protocol which you can constrain to:从 Swift 5 开始,有一个内置的
AdditiveArithmetic
协议,您可以将其限制为:
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 :)现在您不需要手动使内置类型符合协议:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.