How to compare for nearly equal in Swift

Issue #607

Implement Equatable and Comparable and use round

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
struct RGBA: Equatable, Comparable {
let red: CGFloat
let green: CGFloat
let blue: CGFloat
let alpha: CGFloat

init(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat, _ alpha: CGFloat) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}

static func round(_ value: CGFloat) -> CGFloat {
(value * 100).rounded() / 100
}

static func == (left: RGBA, right: RGBA) -> Bool {
let r = Self.round
return r(left.red) == r(right.red)
&& r(left.green) == r(right.green)
&& r(left.blue) == r(right.blue)
&& r(left.alpha) == r(right.alpha)
}

static func < (left: RGBA, right: RGBA) -> Bool {
let r = Self.round
return r(left.red) < r(right.red)
&& r(left.green) < r(right.green)
&& r(left.blue) < r(right.blue)
&& r(left.alpha) <= r(right.alpha)
}
}

XCTAssertGreaterThan(backgroundRgba, RGBA(0.57, 0.12, 0.88, 1.0)
XCTAssertLessThanThan(backgroundRgba, RGBA(0.57, 0.12, 0.88, 1.0)
© 2020 onmyway133 All Rights Reserved.
Theme by hiero