如何在Swift中添加两个通用值? [英] How do I add two generic values in Swift?
本文介绍了如何在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
}
但是我不知道如何在 Numeric
协议中定义 +
运算符的行为.
But I don't know how to define the behaviour of the +
operator in the Numeric
protocol.
推荐答案
protocol Numeric {
func +(lhs: Self, rhs: Self) -> Self
}
应该足够了.
来源: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/
这篇关于如何在Swift中添加两个通用值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文