Swift:将浮点值转换为双精度
我正在写一个浮点协议的扩展。我想以任何可能的方式把它变成替身Swift:将浮点值转换为双精度,swift,floating-point,double,Swift,Floating Point,Double,我正在写一个浮点协议的扩展。我想以任何可能的方式把它变成替身 extension FloatingPoint { var toDouble: Double { return Double(exactly: self) ?? 0 //compile error } } 我不想告诉你们我想要实现什么,这样我们就可以专注于上面的问题。我更愿意听到这样做是不可能的,而不是为我试图解决的更大问题找到有效的解决办法 我尝试使用不同的双构造函数,但可能不够努力。问题是您需要扩
extension FloatingPoint {
var toDouble: Double {
return Double(exactly: self) ?? 0 //compile error
}
}
我不想告诉你们我想要实现什么,这样我们就可以专注于上面的问题。我更愿意听到这样做是不可能的,而不是为我试图解决的更大问题找到有效的解决办法
我尝试使用不同的双构造函数,但可能不够努力。问题是您需要扩展
BinaryFloatingPoint
,而不是FloatingPoint
协议:
extension BinaryFloatingPoint {
// Creates a new instance from the given value if possible otherwise returns nil
var double: Double? { Double(exactly: self) }
// Creates a new instance from the given value, rounded to the closest possible representation.
var doubleValue: Double { .init(self) }
}
extension BinaryFloatingPoint {
func floatingPoint<F: BinaryFloatingPoint>() -> F? { F(exactly: self) }
func floatingPointValue<F: BinaryFloatingPoint>() -> F { .init(self) }
}
操场测试
let cgFloat: CGFloat = .pi // 3.141592653589793
let exactlyDouble = cgFloat.double // 3.141592653589793
let closestDoubleValue = cgFloat.doubleValue // 3.141592653589793
let float80pi: Float80 = .pi // 3.1415926535897932385
let closestCGFloatPiValue: CGFloat = float80pi.floatingPointValue() // 3.141592653589793
let closestDoublePiValue: Double = float80pi.floatingPointValue() // 3.141592653589793
let closestFloatPiValue: Float = float80pi.floatingPointValue() // 3.141593
let exactlyCGFloat: CGFloat? = float80pi.floatingPoint() // nil
let exactlyDouble: Double? = float80pi.floatingPoint() // nil
let exactlyFloat: Float? = float80pi.floatingPoint() // nil
您还可以创建泛型方法来返回符合BinaryFloatingPoint
协议的任何浮点类型:
extension BinaryFloatingPoint {
// Creates a new instance from the given value if possible otherwise returns nil
var double: Double? { Double(exactly: self) }
// Creates a new instance from the given value, rounded to the closest possible representation.
var doubleValue: Double { .init(self) }
}
extension BinaryFloatingPoint {
func floatingPoint<F: BinaryFloatingPoint>() -> F? { F(exactly: self) }
func floatingPointValue<F: BinaryFloatingPoint>() -> F { .init(self) }
}
你说得对。我需要编辑这个问题。