Extension for average to return Double from Numeric generic

喜欢而已 提交于 2020-01-04 05:58:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!