问题
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]()
}
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, +)
}
}
My attempt at the average
function cannot be compiled because of:
Cannot invoke initializer for type 'Double' with an argument list of type '(Self.item)'
Attempts to cast to Double do not work. Any advice for best practices here would be appreciated.
回答1:
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
来源:https://stackoverflow.com/questions/54391361/extension-for-average-to-return-double-from-numeric-generic