小编Den*_*uev的帖子

如何在Swift generic where子句中添加OR条件?

我正在使用带有数字的算术运算从Apple SceneKit 扩展SCNVector3.我使用泛型作为数字的类型,但我发现我必须编写每个函数的至少两个版本,因为这不起作用:

extension SCNVector3 {
    static func *<T> (left: SCNVector3, right: T) -> SCNVector3 {
        return SCNVector3(left.x * Float(right), left.y * Float(right), left.z * Float(right))
}
Run Code Online (Sandbox Code Playgroud)

并给出错误无法使用类型'(T)'的参数列表调用Type'Float'的初始化程序

看一下Apple文档中Float的定义,我发现我能得到的最通用的是init<Source: BinaryFloatingPoint>或init<Source: BinaryInteger>.

所以我必须重写扩展如下,为每个操作创建两个几乎相同的函数:

extension SCNVector3 {
    static func *<T> (left: SCNVector3, right: T) -> SCNVector3 where T: BinaryFloatingPoint {
        return SCNVector3(left.x * Float(right), left.y * Float(right), left.z * Float(right))

    static func *<T> (left: SCNVector3, right: T) -> SCNVector3 where T: BinaryInteger { …
Run Code Online (Sandbox Code Playgroud)

generics where swift

6
推荐指数
1
解决办法
816
查看次数

标签 统计

generics ×1

swift ×1

where ×1