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.