我想使一个函数在Swift中接受任何数字(Int,Float,Double,…)
func myFunction <T : "What to put here"> (number : T) -> {
//...
}
而不使用NSNumber
这实际上是不可能在Swift开箱即用。为此,您需要创建一个新的协议,通过在通用函数中使用的任何方法和操作符进行声明。这个过程将适用于您,但具体细节将取决于您的通用功能的功能。以下是如何为获取数字n并返回(n – 1)^ 2的函数执行此操作。
首先,定义你的协议,与运算符和一个初始化器接受Int(这样我们可以减去一个)。
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协议。你必须明确这一点 – 苹果称之为“通过扩展声明协议”。我们将为Double,Float和所有整数类型执行此操作:
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协议作为通用约束。
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