Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Swift通用数字类型和数学大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我试图围绕 Swift泛型的来龙去做,并制作一些常见的数学函数.我正在尝试实现一个mod函数,但不太确定使用泛型使其工作的最佳方法. 这是我的mod函数的样子: func mod<N: NumericType, I: IntegerType>(_ x: N, _ y: I) -> N { return x - y * floor(x/y) } 但是我收到了这个错误: error: bina
我试图围绕 Swift泛型的来龙去做,并制作一些常见的数学函数.我正在尝试实现@L_122_2@mod函数,但不太确定使用泛型使其工作的最佳方法.

这是我的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 { }

解决方法

从Swift 3开始,所有浮点类型都符合FloaTingPoint,
并且所有整数类型都符合Integer.
两种协议都定义了基本的算术运算,如 –,*,/.
另外,floor()函数是为FloaTingPoint定义的
参数.

因此,在您的情况下,我将定义两个实现,一个用于
整数和一个浮点值:

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,请注明来意。