0

I need to write an initializer for any FloatingPoint value, which can take other type of FloatingPoint, and convert it to Self. Is this possible in swift? I tried something like this:

init<FloatingPointType: FloatingPoint>(_ value: FloatingPointType) {
    guard let sameValue = value as? Self else {
        // Pass throu double to get best precision
        self.init(Double(value))
        return
    }
    self = sameValue // The same type
}

But this just creates infinite loop. The problem is with creating new self, there is no initializer that takes any other FloatingPoint. I think this might be impossible, but maybe there is some way to achieve this.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Damian Dudycz
  • 2,622
  • 19
  • 38
  • You mean you want to cast any Float, Double, and Float80 to Float? – ielyamani Sep 07 '18 at 20:13
  • I need a function or initializer which will allow me to convert Any FloatingPoint like Float, Double, etc to any other FloatingPoint type. And I need this to be generic. So for example I could do: let a = Double(3); let b = Float(a) – Damian Dudycz Sep 07 '18 at 20:19
  • "*to get best precision*" -> Float80. Double is on 64 only. Float is on 32. – ielyamani Sep 07 '18 at 20:35
  • `let a = Double(3); let b = Float(a)` is already possible! – ielyamani Sep 07 '18 at 20:44
  • Your question doesn't make any sense. Looks like you are having a hard time extending `FloatingPoint` protocol trying to return a `FloatingPoint` object. You can't. You need to return `Self` which can be any type that conforms to `FloatingPoint` protocol like `Double`, `Float`, `Float80` – Leo Dabus Sep 07 '18 at 20:47
  • this might help. Note that I am extending BinaryInteger but the approach it is the same https://stackoverflow.com/a/52156694/2303865 `var result: Self = 1` – Leo Dabus Sep 07 '18 at 20:53

1 Answers1

1

Such initializers already exist in the standard library:

let a: Double = Double(3.625)

//From Double to Float and Float80
let b: Float = Float(a)
let c: Float80 = Float80(a)

//From Float to Double and Float80
let d: Double = Double(b)
let e: Float80 = Float80(b)

//From Float80 to Double and Float
let f: Double = Double(c)
let g: Float = Float(c)

You can find it right here:

public init<Source : BinaryFloatingPoint>(_ value: Source) {
    self = Self._convert(from: value).value
}
ielyamani
  • 17,807
  • 10
  • 55
  • 90