gpt4 book ai didi

swift - FloatingPoint 协议(protocol)中的文字数字

转载 作者:可可西里 更新时间:2023-11-01 00:56:03 28 4
gpt4 key购买 nike

假期没有太多事可做,我终于开始更新我的数学库以使用 FloatingPoint 协议(protocol),并摆脱所有重复代码。令我惊讶的是,我几乎立刻就被字面数字所吸引:

func uprightAngle1<T: FloatingPoint>(_ x: T) -> T {
if (x > 0.5 * T.pi) && (x < 1.5 * T.pi) { // *** ERROR HERE
// binary operator '*' cannot be applied to operands of type 'Double' and 'T'
return x - T.pi
} else {
return x
}
}

然而,这个工作正常:

func uprightAngle2<T: FloatingPoint>(_ x: T) -> T {
if (x > T.pi / 2) && (x < 3 * T.pi / 2) { // All fine here
return x - T.pi
} else {
return x
}
}

谁都可以

A) 解释为什么编译器使用整型字面量而不是浮点字面量正确推断类型,

B) 告诉我当我不能使用有理数时要使用的习语,因为 let half: T = 0.5T(0.5) compile...

最佳答案

FloatingPoint 协议(protocol)继承自 ExpressibleByIntegerLiteral通过继承链

FloatingPoint - SignedNumeric - Numeric - ExpressibleByIntegerLiteral

这就是第二个函数 uprightAngle2 编译的原因:ValuesT 类型的是从整数文字 23 创建的。

第一个函数 uprightAngle1 没有编译因为FloatingPoint 协议(protocol)继承自 ExpressibleByFloatLiteral,即 T 类型的值不能从像 1.5 这样的浮点文字创建。

可能的解决方案:

  • 创建有理数作为 let half: T = 1/2。 (不是 让一半 = T(1/2),这将在创建 T 之前截断除法结果值(value)。)

  • FloatingPoint 替换为 BinaryFloatingPoint(它继承来自 ExpressibleByFloatLiteral)。

有关浮点设计的更多信息协议(protocol)参见 SE-0067 Enhanced Floating Point Protocols .

Swift 标准库中的浮点类型(DoubleFloatCGFloatFloat80)为还有Core Graphics 框架中的CGFloat 都符合BinaryFloatingPoint 协议(protocol),所以这个协议(protocol)“足够通用”,适用于许多应用。

关于swift - FloatingPoint 协议(protocol)中的文字数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48021184/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com