我想让一个函数接受任何数字(Int,Float,Double,…)迅速地
func myFunction <T : "What to put here"> (number : T) -> {
//...
}
不使用NSNumber
我想让一个函数接受任何数字(Int,Float,Double,…)迅速地
func myFunction <T : "What to put here"> (number : T) -> {
//...
}
不使用NSNumber
Update:下面的答案原则上仍然适用,但Swift 4完成了数字协议的重新设计,因此添加自己的协议通常是不必要的.在构建自己的系统之前,先看一下standard library's numeric protocols.
在Swift中,这实际上是不可能的.要做到这一点,您需要创建一个新的协议,用您将在泛型函数中使用的任何方法和运算符声明.这个过程对您来说是可行的,但具体细节将在一定程度上取决于您的泛型函数的功能.对于一个得到数字n
并返回(n - 1)^2
的函数,我们将这样做.
首先,定义你的协议,使用操作符和一个取Int
的初始值设定项(这样我们就可以减go 1).
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)
}
所有数字类型都是already implement these,但此时编译器不知道它们是否符合新的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