I need a little help updating some overloaded funcs such that I can use generic functions instead.
I am writing an application where I produce a grayscale image from some raw data. The raw data (typically terrain data) contains data points of Doubles
or Ints
, depending on the source dataset that I am using.
I have created some custom "shaders" that convert the raw data value to a grayscale pixel value, but I have to create two overloaded functions for every shader I need.
func shaderLinear(_ v: Double, limits: ClosedRange<Double>, scalar: Int, isInverse: Bool) -> UInt8 {
return UInt8(normaliseValue(v, limits: limits, isInverse: isInverse) * Double(scalar))
}
func shaderLinear(_ v: Int, limits: ClosedRange<Double>, scalar: Int, isInverse: Bool) -> UInt8 {
return UInt8(normaliseValue(v, limits: limits, isInverse: isInverse) * Double(scalar))
}
// ... other shaders, code not provided...
func normaliseValue(_ value: Double, limits: ClosedRange<Double>, isInverse: Bool) -> Double {
let lower = limits.lowerBound
let upper = limits.upperBound
let v = min(max(value, lower), upper) - lower
let span = upper - lower
return (isInverse) ? 1.0 - (v / span) : v / span
}
func normaliseValue(_ value: Int, limits: ClosedRange<Double>, isInverse: Bool) -> Double {
return normaliseValue(Double(value), limits: limits, isInverse: isInverse)
}
This works okay but I was hoping to replace the overloaded shader functions with something like ...
func shaderTest<T: Numeric>(_ v: T, limits: ClosedRange<Double>, scalar: Int, isInverse: Bool) -> UInt8 {
return UInt8(normaliseValue(Double(v), limits: limits, isInverse: isInverse))
}
If this works, I would only need one normaliseValue
function and a single generic function for each shader I want to implement.
But I get an error Initializer 'init(_:)' requires that 'T' conform to 'BinaryInteger'
. So I guess Numeric
is not the correct generic to use in my case.
Is my approach simply wrong?
Suggestions on a better way to use generics instead of my overloaded functions would be very welcome.
Kieran