问题
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