In the process of programming in swift, I encountered such a problem which confused me.
as shown in the picture above。
I found that the maxY property of CGRect is actually not included in CGRect. Because for a CGRect whose origin coordinate is (0, 0) and the length and width are 100, its actual maxY should be (0, 99).
I also found that the same problem exists in Array, for example, an array of [0, 1, 2, 3, 4, 5], his subscript should be 0-5, but the endIndex property of Array is 6.
I wonder why it is designed this way, does it make any sense?
CodePudding user response:
Senario 1
CGRect.contains(_:)
return true only if the coordinate is inside the rectangle or it is on the minimumX
& minimumY
edges.
If the point lies on the maximum edges it will return false
.
In your case you are trying to check a point which lies on the maximum edge of the rect. So it will return ```false``.
A point is considered inside the rectangle if its coordinates lie inside the rectangle or on the minimum X or minimum Y edge.
Senario 2
endIndex of an array is defined as follows.
The array’s “past the end” position—that is, the position one greater than the last valid subscript argument.
So in your array,
5
is the last valid element which has the index of 5
. So endIndex
is defined as the 1 value higher than the index of the last element. So it will return 6
.
CodePudding user response:
CGRect.contains
is actually refers CGRectContainsPoint
. As the documentation says
A point is considered inside the rectangle if its coordinates lie inside the rectangle or on the minimum X or minimum Y edge.
So why?. Lets think we have a frame like CGRect(x: 0, y: 0, width: 3, height: 3)
What we expect that , We want a frame that x position is 0 and width must be 3.
From 0 to 3 Its like :
0->1->2->3
Numbers are point , arrows like feet
The distance is 3
yes but there is 4 points
thats why Apple wants to eliminate 1 point. We can say that this is the last point from documentation. Thats why print(rect.contains(.init(x: 0, y: 0)))
is true and print(rect.contains(.init(x: rect.maxX, y: rect.maxY)))
or any other end point is not true