扩展平均值以从数值泛型返回Double

时间:2019-01-27 18:15:40

标签: swift generics swift-protocols

假设我为同类型数据列创建协议和结构:

protocol Columnizable {
    associatedtype Item

    var name: String { get }
    var values: [Item] { get }

}

struct Column<T>: Columnizable {

    var name: String
    var values = [T]()

}

我想创建一个协议扩展,允许Numeric具有一个average函数,如果类型符合values协议,则该函数可以计算Numeric的平均值,例如双精度和整数

extension Columnizable where Item: Numeric {

    func average() -> Double {
        return Double(sum()) / values.count
    }

    func sum() -> Item {
        return values.reduce(0, +)
    }

}

由于以下原因,我对average函数的尝试无法编译

Cannot invoke initializer for type 'Double' with an argument list of type '(Self.item)'

尝试强制转换为Double无效。任何有关最佳做法的建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

我需要使用BinaryIntegerBinaryFloatingPoint协议,因为它们可以轻松转换为Double。正如@rob napier所说,Complex类型将不能Double转换。

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