Real protocol and floating point literals

It doesn't appear that the Real protocol provides init() functions for Float, Double, etc., as a result I can't find a way to use floating point literals, e.g.:

func identity<F: Real>(_ x: F) -> F {
  return 1.0 * x
}

Produces the compile error:

Cannot convert value of type 'Double' to expected argument type 'F'
Replace '1.0' with 'F(1.0)'

Replacing 1.0 with F(1.0) generates the error:

Cannot convert value of type 'Double' to expected argument type 'Int'
Replace '1.0' with 'Int(1.0)'

All of the sample code I have seen for RealModule uses integer literals. Is there a way to use floating point literals?

I have tried creating my own Protocol that inherits from BinaryFloatingPoint and it is able to handle floating point literals because of the init() functions in BinaryFloatingPoint. Is there a reason Real doesn't extend BinaryFloatingPoint?

Because Real would also support decimal floating-point types.

It sounds like you want <F: Real & BinaryFloatingPoint> for your constraint. Longer-term, floating-point literals are due for a reworking that would resolve this problem.

7 Likes