Generic function with binary operations

不问归期 提交于 2019-12-11 06:02:37

问题


I have the following function to return the normalized version of an array whose elements could be Int, Double, Float.

I'm getting the error indicated on line 5 below. I thought the Numeric protocol would address the binary operation but I guess not. What am I doing wrong?

func normalizeArray<T: Comparable & Numeric>(a: [T]) -> [T] {
    let min: T = a.min()!
    let max: T = a.max()!

    let n = a.map({ ($0 - min) / (max - min) }) <--- Binary operator '/' cannot be applied to two 'T' operands

    return n
}

thanks


回答1:


The Numeric protocol requires addition, subtraction and multiplication operators, but not a division operator.

I am not aware of a protocol which requires a division operator to which both integer and floating point types conform, therefore you have to implement two overloaded functions:

func normalizeArray<T: FloatingPoint>(a: [T]) -> [T] { ... }

func normalizeArray<T: BinaryInteger>(a: [T]) -> [T] { ... }

Note that your implementation will crash if called with an empty array, I'll suggest

func normalizeArray<T: BinaryInteger>(a: [T]) -> [T] {
    guard let min = a.min(), let max = a.max() else {
        return []
    }
    return a.map({ ($0 - min) / (max - min) })
}


来源:https://stackoverflow.com/questions/49899377/generic-function-with-binary-operations

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