swift - How to convert a FloatingPoint-conforming value to a CGFloat? - Stack Overflow

admin2025-04-20  0

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.

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.

Share Improve this question edited Mar 2 at 12:10 Niek asked Mar 2 at 12:03 NiekNiek 1,6191 gold badge18 silver badges30 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745123233a286273.html

最新回复(0)