我想让一个函数接受任何数字(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协议.你必须明确这一点——苹果称之为"通过扩展声明协议采用"我们将对DoubleFloat和所有整数类型执行此操作:

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

Swift相关问答推荐

如何更新Square Order?

是否在核心数据中使用Uint?

为什么要在SWIFT RandomAccessCollection协议中重新定义元素类型?

background Task(.backgroundTask)不适用于MySQL

从Firebase播放音频文件不起作用

从任务中打印

使用 @resultBuilder 的通用 buildList 函数

当字符串包含 \r\n 时,NSRegularExpression 不起作用

如何在 swift 5.0 中获取当前行

从一个范围减go 多个范围

swiftui中服务端图片如何设计view并赋予rotationEffect?

为什么 String.contains 在我导入 Foundation 时表现不同?

闭包 - deinit self 对象的时间

如何有条件地依赖桌面与 iOS 的系统库?

更改该函数的参数之一时,如何将这些 SwiftUI 异步任务合并到一个任务中以从函数中获得正确的结果

在 iOS 中使用 Swift 保存 PDF 文件并显示它们

如何以编程方式读取 wkwebview 的控制台日志(log)

如何从 UITableViewCell 类中引用 UITableViewController?

Swift 的 JSONDecoder 在 JSON 字符串中有多种日期格式?

如何在 Swift 中从字符串创建类的实例