且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一个泛型函数的类型应该采用什么协议来将任何数字类型作为 Swift 中的参数?

更新时间:2022-11-21 08:07:48

更新: 下面的答案原则上仍然适用,但 Swift 4 完成了对数字协议的重新设计,例如添加您自己的通常是不必要的.在构建自己的系统之前,请查看标准库的数字协议.

Update: The answer below still applies in principle, but Swift 4 completed a redesign of the numeric protocols, such that adding your own is often unnecessary. Take a look at the standard library's numeric protocols before you build your own system.

这实际上在 Swift 中是不可能开箱即用的.为此,您需要创建一个新协议,使用您将在泛型函数中使用的任何方法和运算符进行声明.这个过程对你有用,但确切的细节将在一定程度上取决于你的通用函数的作用.下面是对获取数字 n 并返回 (n - 1)^2 的函数执行此操作的方法.

This actually isn't possible out of the box in Swift. To do this you'll need to create a new protocol, declared with whatever methods and operators you're going to use inside your generic function. This process will work for you, but the exact details will depend a little on what your generic function does. Here's how you'd do it for a function that gets a number n and returns (n - 1)^2.

首先,定义您的协议,使用运算符和一个带有 Int 的初始化器(这样我们就可以减去一个).

First, define your protocol, with the operators and an initializer that takes an Int (that's so we can subtract one).

protocol NumericType {
    func +(lhs: Self, rhs: Self) -> Self
    func -(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
    func %(lhs: Self, rhs: Self) -> Self
    init(_ v: Int)
}

所有数字类型已经实现这些,但此时编译器不知道它们符合新的NumericType协议.您必须明确说明这一点——Apple 称之为通过扩展声明采用协议".我们将为 DoubleFloat 和所有整数类型执行此操作:

All of the numeric types already implement these, but at this point the compiler doesn't know that they conform to the new NumericType protocol. You have to make this explicit -- Apple calls this "declaring protocol adoption with an extension." We'll do this for Double, Float, and all the integer types:

extension Double : NumericType { }
extension Float  : NumericType { }
extension Int    : NumericType { }
extension Int8   : NumericType { }
extension Int16  : NumericType { }
extension Int32  : NumericType { }
extension Int64  : NumericType { }
extension UInt   : NumericType { }
extension UInt8  : NumericType { }
extension UInt16 : NumericType { }
extension UInt32 : NumericType { }
extension UInt64 : NumericType { }

现在我们可以编写我们的实际函数,使用 NumericType 协议作为通用约束.

Now we can write our actual function, using the NumericType protocol as a generic constraint.

func minusOneSquared<T : NumericType> (number : T) -> T {
    let minusOne = number - T(1)
    return minusOne * minusOne
}

minusOneSquared(5)              // 16
minusOneSquared(2.3)            // 1.69
minusOneSquared(2 as UInt64)    // 1