比较UIColors失败,但是哈希值相等吗? [英] Comparing UIColors fails, but hashes are equal?

查看:107
本文介绍了比较UIColors失败,但是哈希值相等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用UIColor映射到字典中的值,但是遇到了一个非常奇怪的事情.我的键中有一半返回正确的值,而另一半则没有.当我使用isEqual比较UIColors时,它们返回false,但是哈希匹配就很好了.

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))
        }

这将返回以下内容:

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

关于为什么会出错的任何想法?我已经检查了UIColor的内容,它们是相同的.

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

推荐答案

我不太确定这样做的目的,但是您应该注意 UIColor ,这意味着您可以使用==来检查UIColor实例的相等性,例如:

I'm not pretty sure of the purpose of doing this, but you should note that Equatable does adopted by UIColor which means that you can do 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")

希望有帮助.

这篇关于比较UIColors失败,但是哈希值相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆