Reputation: 1609
I'm writing a View
that receives some data, and I'd like it to be generic over what kind of floating point-number that data uses.
typealias DataKey = StringProtocol & Sendable
typealias DataValue = FloatingPoint & Comparable
struct RadarChartDataOverlay<K: DataKey, V: DataValue>: Shape {
let data: [K: V]
}
At some point down the line, I need to take that data and convert it to a CGFloat
for rendering. However, this gives a compile-time error:
func convertToCGFloat<N: DataValue>(_ value: N) -> CGFloat {
return CGFloat(value) // No exact matches in call to initializer
}
Is there any way to achieve this, or do I just need to accept that I'll have to specify a specific type for my Struct
?
I tried casting to a Float
first, but that cast gives the same error.
Upvotes: 0
Views: 33
Reputation: 273510
While you probably can convert a FloatingPoint
to a CGFloat
by calculating the closest CGFloat
value represented by the exponent
and significand
. I'd recommend changing the generic constraint to BinaryFloatingPoint
instead. This is sufficient for most use cases.
typealias DataValue = BinaryFloatingPoint & Comparable
Then CGFloat(value)
will compile successfully.
BinaryFloatingPoint
is FloatingPoint
but is constrained to be base-2.
Upvotes: 2