扩展平均值以从数值泛型返回Double [英] Extension for average to return Double from Numeric generic
问题描述
假设我为同类数据列创建协议和结构:
Suppose I create a protocol and structure for a Column of homogeneously typed data:
protocol Columnizable {
associatedtype Item
var name: String { get }
var values: [Item] { get }
}
struct Column<T>: Columnizable {
var name: String
var values = [T]()
}
我想创建一个协议扩展,允许Numeric具有 average
函数,该函数可以在类型符合 Numeric <的情况下计算
values
的平均值./code>协议-例如Double和Int
I would like to create a Protocol extension that allows Numeric to have an average
function that could compute the average of values
if the type conforms to Numeric
protocol- for instance, namely Double and Int
extension Columnizable where Item: Numeric {
func average() -> Double {
return Double(sum()) / values.count
}
func sum() -> Item {
return values.reduce(0, +)
}
}
由于以下原因,我对 average
函数的尝试无法编译:
My attempt at the average
function cannot be compiled because of:
无法为类型为'(Self.item)'的参数列表的类型为'Double'的初始化程序
尝试强制转换为Double无效.任何有关最佳做法的建议都将不胜感激.
Attempts to cast to Double do not work. Any advice for best practices here would be appreciated.
推荐答案
我需要使用 BinaryInteger
或 BinaryFloatingPoint
协议,因为它们可以轻松转换为双
.正如@rob napier所说, Complex
类型将不是 Double
可转换的.
I needed to use the BinaryInteger
or BinaryFloatingPoint
protocols since they can easily be transformed to a Double
. As @rob napier called out, that a Complex
type would not be Double
convertible.
extension Columnizable where Item: BinaryInteger {
var average: Double {
return Double(total) / Double(values.count)
}
}
extension Columnizable where Item: BinaryFloatingPoint {
var average: Item {
return total / Item(values.count)
}
}
stackoverflow.com/a/28288619/2019221
这篇关于扩展平均值以从数值泛型返回Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!