- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
假期没有太多事可做,我终于开始更新我的数学库以使用 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.5
和 T(0.5)
compile...
最佳答案
FloatingPoint
协议(protocol)继承自 ExpressibleByIntegerLiteral
通过继承链
FloatingPoint - SignedNumeric - Numeric - ExpressibleByIntegerLiteral
这就是第二个函数 uprightAngle2
编译的原因:ValuesT
类型的是从整数文字 2
和 3
创建的。
第一个函数 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 标准库中的浮点类型(Double
、Float
、CGFloat
、Float80
)为还有Core Graphics 框架中的CGFloat
都符合BinaryFloatingPoint
协议(protocol),所以这个协议(protocol)“足够通用”,适用于许多应用。
关于swift - FloatingPoint 协议(protocol)中的文字数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48021184/
我需要为任何 FloatingPoint 值编写一个初始化程序,它可以采用其他类型的 FloatingPoint,并将其转换为 Self。这在 swift 中可行吗?我试过这样的事情: init(_
我正在尝试扩展符合 FloatingPoint 标准的元素的集合以计算平均值。 extension Collection where Element: FloatingPoint { func
假期没有太多事可做,我终于开始更新我的数学库以使用 FloatingPoint 协议(protocol),并摆脱所有重复代码。令我惊讶的是,我几乎立刻就被字面数字所吸引: func uprightAn
考虑以下内容(从实际代码中简化而来): func roundedInt(_ f: T) -> Int { return Int(f.rounded()) } 编译失败,出现以下错误: Cann
我想让下面的函数同时使用 Float 和 Double 值: func srgb2linear(_ S: Float) -> Float { if S (_ S: T) -> T 但是当我尝试这样
我是 spiderMonkey 的新手,并已按照本教程开始使用(我使用的是 MAC OS X):https://developer.mozilla.org/en/docs/How_to_embed_t
这个问题在这里已经有了答案: Making Swift generics play with overloaded functions (2 个答案) 关闭 4 年前。 import Founda
我在 SO 上看到过类似的问题,但它并没有回答我在这里提出的所有问题。 我有这样一个函数: func myFunctionDouble (_ valores:[Double] = []) -> A
我刚刚开始自学用 Swift 编写代码。我目前正在尝试在按下按钮时旋转图像(只是练习非常简单的东西)并且 Xcode 向我抛出两个错误: Referencing operator function '
我是一名优秀的程序员,十分优秀!