什么协议应该采用通用函数的类型作为Swift中的任何数字类型作为参数?

前端之家收集整理的这篇文章主要介绍了什么协议应该采用通用函数的类型作为Swift中的任何数字类型作为参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使一个函数在Swift中接受任何数字(Int,Float,Double,…)
  1. func myFunction <T : "What to put here"> (number : T) -> {
  2. //...
  3. }

而不使用NSNumber

这实际上是不可能在Swift开箱即用。为此,您需要创建一个新的协议,通过在通用函数中使用的任何方法和操作符进行声明。这个过程将适用于您,但具体细节将取决于您的通用功能功能。以下是如何为获取数字n并返回(n – 1)^ 2的函数执行此操作。

首先,定义你的协议,与运算符和一个初始化器接受Int(这样我们可以减去一个)。

  1. protocol NumericType {
  2. func +(lhs: Self,rhs: Self) -> Self
  3. func -(lhs: Self,rhs: Self) -> Self
  4. func *(lhs: Self,rhs: Self) -> Self
  5. func /(lhs: Self,rhs: Self) -> Self
  6. func %(lhs: Self,rhs: Self) -> Self
  7. init(_ v: Int)
  8. }

所有的数字类型都已经实现了这些,但是在这一点上,编译器不知道它们符合新的NumericType协议。你必须明确这一点 – 苹果称之为“通过扩展声明协议”。我们将为Double,Float和所有整数类型执行此操作:

  1. extension Double : NumericType { }
  2. extension Float : NumericType { }
  3. extension Int : NumericType { }
  4. extension Int8 : NumericType { }
  5. extension Int16 : NumericType { }
  6. extension Int32 : NumericType { }
  7. extension Int64 : NumericType { }
  8. extension UInt : NumericType { }
  9. extension UInt8 : NumericType { }
  10. extension UInt16 : NumericType { }
  11. extension UInt32 : NumericType { }
  12. extension UInt64 : NumericType { }

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

  1. func minusOneSquared<T : NumericType> (number : T) -> T {
  2. let minusOne = number - T(1)
  3. return minusOne * minusOne
  4. }
  5.  
  6. minusOneSquared(5) // 16
  7. minusOneSquared(2.3) // 1.69
  8. minusOneSquared(2 as UInt64) // 1

猜你在找的Swift相关文章