对于数值类型,它使用来自 Swift Numerics 的 isApproximatelyEqual。
使用 DeriveApproximateEquality 注解您的类型,以自动遵循 ApproximateEquality 协议并自动生成实现。
import ApproximateEquality
import ApproximateEqualityMacros
import CoreGraphics
@DeriveApproximateEquality
public struct MyType {
var x: Double
var y: CGPoint
@ApproximateEqualityIgnored
var z: Double
var w: Float
}
let thing1 = MyType(x: 10, y: CGPoint(x: 20, y: 0), z: 30, w: 0)
let thing2 = MyType(x: 10, y: CGPoint(x: 20, y: 0), z: 40, w: 0)
let error = 0.000_001
let thing3 = MyType(x: 10 + error, y: CGPoint(x: 20, y: 0), z: 40, w: 0)
print(thing1.isApproximatelyEqual(to: thing2, absoluteTolerance: 0.0001)) // true
print(thing1.isApproximatelyEqual(to: thing3, absoluteTolerance: 0.0001)) // true
print(thing1.isApproximatelyEqual(to: thing3, absoluteTolerance: 0.000_000_1)) // false
展开 @DeriveApproximateEquality 宏会生成一个扩展
extension MyType: ApproximateEquality {
public func isApproximatelyEqual(to other: Self, absoluteTolerance: Double.Magnitude) -> Bool {
x.isApproximatelyEqual(to: other.x, absoluteTolerance: Double.Magnitude(absoluteTolerance))
&& y.isApproximatelyEqual(to: other.y, absoluteTolerance: CGPoint.Magnitude(absoluteTolerance))
&& w.isApproximatelyEqual(to: other.w, absoluteTolerance: Float.Magnitude(absoluteTolerance))
}
}
请注意,带有 @ApproximateEqualityIgnored 前缀的属性在实现中使用。
MIT 许可。
此代码的部分内容来自 Apple-Numerics (https://github.com/apple/swift-numerics) 项目,并根据 Apache 许可获得许可。
DeriveApproximateEquality 中转换为 Double 类型