Reputation: 2800
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.
Upvotes: 0
Views: 128
Reputation: 18591
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
}
Upvotes: 1