Recusiwe
Recusiwe

Reputation: 890

Comparing UIColors fails, but hashes are equal?

I'm using UIColor to map to a value in a dictionary, but I bumped into a really odd thing. Half of my keys returns the right values, and the other half does not. When I compare the UIColors using isEqual they return false, but the hash matches just fine.

 for key in colorToAllocationCurrent.keys {
            print("\(key.hash) ---> \(currentColor!.hash)")
            print(key.isEqual(currentColor))
        }

This returns the following:

144048128 ---> 151431738
false
155123712 ---> 151431738
false
147739933 ---> 151431738
false
151431738 ---> 151431738 <-------- EQUAL?
false

Any ideas on why this goes wrong? I've checked to content of the UIColor, and they're the same.

When I print the description of the color instead of the hash, the colors appears the same again. The odd thing is that it work on half the colors.

 for key in colorToAllocationCurrent.keys {
            print("\(key.description) ---> \(currentColor!.description)")
            print(key.isEqual(currentColor))
        }

UIExtendedSRGBColorSpace 1 0 0 1 ---> UIExtendedSRGBColorSpace 1 0.666667 0 1
false
UIExtendedSRGBColorSpace 1 1 0 1 ---> UIExtendedSRGBColorSpace 1 0.666667 0 1
false
UIExtendedSRGBColorSpace 1 0.333333 0 1 ---> UIExtendedSRGBColorSpace 1 0.666667 0 1
false
UIExtendedSRGBColorSpace 1 0.666667 0 1 ---> UIExtendedSRGBColorSpace 1 0.666667 0 1
false

Upvotes: 1

Views: 807

Answers (1)

Ahmad F
Ahmad F

Reputation: 31655

I'm not pretty sure of the purpose of doing this, but you should note that Equatable adopts UIColor which means that you can check the equality of UIColor instances by using ==, for example:

let col1 = UIColor.red
let col2 = UIColor.red

// the output is "matched"
print(col1 == col2 ? "matched" : "no match")

let customCol1 = UIColor(colorLiteralRed: 123.0/255.0, green: 243.0/255.0, blue: 46.0/255.0, alpha: 0.9)
let customCol2 = UIColor(colorLiteralRed: 123.0/255.0, green: 243.0/255.0, blue: 46.0/255.0, alpha: 0.9)

// the output is "matched"
print(customCol1 == customCol2 ? "matched" : "no match")

let customCol3 = UIColor(colorLiteralRed: 123.0/255.0, green: 243.0/255.0, blue: 46.0/255.0, alpha: 0.9)
let customCol4 = UIColor(colorLiteralRed: 123.0/255.0, green: 243.0/255.0, blue: 46.0/255.0, alpha: 1.0)

// the output is "no match"
print(customCol3 == customCol4 ? "matched" : "no match")

Upvotes: 1

Related Questions