gpt4 book ai didi

swift - 泛型函数的类型应该采用什么协议(protocol)来将任何数字类型作为 Swift 中的参数?

转载 作者:IT王子 更新时间:2023-10-29 05:02:25 25 4
gpt4 key购买 nike

我想让一个函数在 Swift 中接受任何数字(Int、Float、Double、...)

func myFunction <T : "What to put here"> (number : T) ->  {
//...
}

不使用 NSNumber

最佳答案

更新:下面的答案原则上仍然适用,但 Swift 4 完成了对数字协议(protocol)的重新设计,因此通常不需要添加自己的协议(protocol)。看看 standard library's numeric protocols在构建自己的系统之前。


这在 Swift 中实际上是不可能的。为此,您需要创建一个新协议(protocol),使用您将在通用函数中使用的任何方法和运算符进行声明。这个过程对你有用,但具体细节在一定程度上取决于你的通用函数的作用。以下是获取数字 n 并返回 (n - 1)^2 的函数的处理方式。

首先,使用运算符和采用 Int 的初始化程序定义您的协议(protocol)(这样我们就可以减去一个)。

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 协议(protocol)。你必须明确这一点——Apple 称之为“通过扩展声明协议(protocol)采用”。我们将为 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 协议(protocol)作为通用约束。

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 - 泛型函数的类型应该采用什么协议(protocol)来将任何数字类型作为 Swift 中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com