更新时间:2023-01-11 22:12:03
您的==代码比较哈希而不是比较每个属性是否有特定的原因?即
Is there a particular reason why your == code compares hashes rather than each property? i.e.
static func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return (lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z) &&
(lhs.nx == rhs.nx) && ...etc
}
然后,如果lhs.x
不等于rhs.x
,则代码将快速失败并继续执行下一个操作.当前,您必须一次又一次地创建哈希值.另外,您可以通过在构造函数中计算一次哈希来加快当前代码的速度(例如,使所有属性为private(set)
,如下面的简化示例所示).
Then if lhs.x
is not equal to rhs.x
, the code will fail quickly and move on to the next. Currently you're having to create a hash value again and again. Alternatively, you could speed up your current code by calculating the hash once in the constructor (and, say, making all the properties private(set)
like in the simplified example below).
struct Vertex {
private(set) var x, y: Float
let hash: Int
init(x: Float, y: Float) {
self.x = x
self.y = y
hash = "\(x),\(y)".hashValue
}
static func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return lhs.x == rhs.x
}
}
let vertex = Vertex(x: 1.0, y: 2.0)
print(vertex.hash)