大佬教程收集整理的这篇文章主要介绍了Swift通用数字类型和数学,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的mod函数的样子:
func mod<N: NumericType,I: IntegerType>(_ x: N,_ y: I) -> N { return x - y * floor(x/y) }
但是我收到了这个错误:
error: binary operator '/' cAnnot be applied to operands of type 'N' and 'I' return x - y * floor(x/y)
这是我的十进制和整数类型数字的NumericType声明:
protocol NumericType: Comparable { static func +(lhs: Self,rhs: Self) -> Self static func -(lhs: Self,rhs: Self) -> Self static func *(lhs: Self,rhs: Self) -> Self static func /(lhs: Self,rhs: Self) -> Self static func %(lhs: Self,rhs: Self) -> Self } protocol decimalType: NumericType { init(_ v: DoublE) } protocol IntegerType: NumericType { init(_ v: int) } extension CGFloat : decimalType { } extension Double : decimalType { } extension Float : decimalType { } extension Int : IntegerType { } extension Int8 : IntegerType { } extension Int16 : IntegerType { } extension Int32 : IntegerType { } extension Int64 : IntegerType { } extension UInt : IntegerType { } extension UInt8 : IntegerType { } extension UInt16 : IntegerType { } extension UInt32 : IntegerType { } extension UInt64 : IntegerType { }
因此,在您的情况下,我将定义两个实现,一个用于
整数和一个浮点值:
func mod<N: Integer>(_ x: N,_ y: N) -> N { return x - y * (x/y) // or just: return x % y } func mod<N: FloaTingPoint>(_ x: N,_ y: N) -> N { return x - y * floor(x/y) }
FloaTingPoint还有一个truncaTingRemainder方法,a.truncaTingRemainder(b)是“浮点等价物”到整数的%b.它给了如果两者都给出与mod函数相同的结果操作数具有相同的符号.
以上是大佬教程为你收集整理的Swift通用数字类型和数学全部内容,希望文章能够帮你解决Swift通用数字类型和数学所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。