Reputation: 7778
This must have been asked before, but I cannot find a suitable reference. I have found this question, but that compares three numbers with each other.
I am trying to compare 2 UIColor(s) to avoid duplication. Each color is referenced in r, g, b, alpha. I form the colors so I can control number formatting.
What would be the appropriate way to handle this?
Upvotes: 3
Views: 2501
Reputation: 7564
If you are creating all color the same way you can just use ==
.
If your colors are in different color spaces and you just want to compare their RGBA value use the following:
extension UIColor {
func equals(_ rhs: UIColor) -> Bool {
var lhsR: CGFloat = 0
var lhsG: CGFloat = 0
var lhsB: CGFloat = 0
var lhsA: CGFloat = 0
self.getRed(&lhsR, green: &lhsG, blue: &lhsB, alpha: &lhsA)
var rhsR: CGFloat = 0
var rhsG: CGFloat = 0
var rhsB: CGFloat = 0
var rhsA: CGFloat = 0
rhs.getRed(&rhsR, green: &rhsG, blue: &rhsB, alpha: &rhsA)
return lhsR == rhsR &&
lhsG == rhsG &&
lhsB == rhsB &&
lhsA == rhsA
}
}
For instance:
let white1 = UIColor.white
let white2 = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1)
white1 == white2 //false
white1.cgColor == white2.cgColor //false
white1.equals(white2) //true
Upvotes: 5
Reputation: 5450
If you initialize as UIColor, you should be able to compare the colors to each other easily:
import UIKit
let myFirstColor = UIColor.red
let mySecondColor = UIColor.red
let myThirdColor = UIColor(colorLiteralRed: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
let iosWhite = UIColor.white
let myWhite = UIColor(white: 1.0, alpha: 1.0)
myFirstColor == mySecondColor //True
myFirstColor == myThirdColor //True
iosWhite == myWhite // True
From comments, there edge cases. I think these are all gray
s black
, white
and clear
. To compensate, you can create your own grays
and compare to it:
let myOtherWhite = UIColor(colorLiteralRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
which is not equal to UIColor.white
That said, it is easy to find the edge cases on playground:
Upvotes: 0