且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较两个CGPoint是否相等:对于输出相同点的两个对象返回不相等?

更新时间:2022-10-16 15:47:25

不幸的是,您在控制台中看到的并不是您的真正价值.

import UIKit

var x = CGPoint(x:175.0,y:70.0)
var y = CGPoint(x:175.0,y:70.00000000000001)

print("\(x.equalTo(y)), \(x == y),\(x),\(y)")

问题是,控制台仅允许10 -16 ,但实际上,您的CGFloat可能会更低,因为在64位体系结构上,CGFloatDouble.>

这意味着如果要获得将出现在控制台上的相等性,必须将CGPoint值转换为Float,因此您需要执行以下操作:

if Float(boxA.x) == Float(boxB.x) && Float(boxA.y) == Float(boxB.y)
{
  //We have equality
}

现在我想更进一步.

在大多数情况下,我们使用CGPoint来确定场景中的点.我们很少要面对1/2分,它们使我们的生活变得混乱.

因此,我喜欢强制转换为Int,而不是Float.这样可以保证两个点是否位于场景空间中的同一CGPoint

if Int(boxA.x) == Int(boxB.x) && Int(boxA.y) == Int(boxB.y)
{
  //We have equality
}

According to this question, using == and != should let you check for equality between two CGPoint objects.

However, the code below fails to consider two CGPoint objects as equal even though they output the same value.

What is the right way to check equality among CGPoint objects?

Code:

    let boardTilePos = boardLayer.convert(boardTile.position, from: boardTile.parent!)
    let shapeTilePos = boardLayer.convert(tile.position, from: tile.parent!)   
    print("board tile pos: \(boardTilePos). active tile pos: \(shapeTilePos). true/false: \(shapeTilePos == boardTilePos)")

Output:

board tile pos: (175.0, 70.0). active tile pos: (175.0, 70.0). true/false: false

Unfortunately, what you see in the console is not what your real value is.

import UIKit

var x = CGPoint(x:175.0,y:70.0)
var y = CGPoint(x:175.0,y:70.00000000000001)

print("\(x.equalTo(y)), \(x == y),\(x),\(y)")

The problem is, the console only allows for 10-16 but in reality your CGFloat can go even lower than that because on 64bit architecture, CGFloat is Double.

This means you have to cast your CGPoint values to a Float if you want to get equality that will appear on the console, so you need to do something like:

if Float(boxA.x) == Float(boxB.x) && Float(boxA.y) == Float(boxB.y)
{
  //We have equality
}

Now I like to take it one step further.

In most cases, we are using CGPoint to determine points on the scene. Rarely do we ever want to be dealing with 1/2 points, they make our lives just confusing.

So instead of Float, I like to cast to Int. This will guarantee if two points are lying on the same CGPoint in scene space

if Int(boxA.x) == Int(boxB.x) && Int(boxA.y) == Int(boxB.y)
{
  //We have equality
}