从CGPoints数组获取最大值和最小值 [英] Get the max and min values from an Array of CGPoints
问题描述
我们有一组CGPoints:
We have an array of CGPoints:
let points = [(1234.0, 1053.0), (1241.0, 1111.0), (1152.0, 1043.0)]
我想做的就是获得x最高的CGPoint值和数组中y值最高的那个。我将使用这些点来创建CGRect:
What I'm trying to do is get the CGPoint with the highest x value and the one with the highest y value in the array. I will be using these points to create a CGRect:
extension CGRect {
init(p1: CGPoint, p2: CGPoint) {
self.init(x: min(p1.x, p2.x),
y: min(p1.y, p2.y),
width: abs(p1.x - p2.x),
height: abs(p1.y - p2.y))
}
}
我知道有一种方法可以通过以下操作获取数组中的最大值和最小值:
I know there a way to get max and min values in an array by doing something like this:
points.min()
points.max()
但是这些似乎不起作用,因为它包含CGPoints数组。可以从数组中获取这些值吗?
but these don't seem to work since its an array of CGPoints. Is it possible to get these values from the array?
推荐答案
您可以映射值以在x和y中找到最小值和最大值。坐标如下。如果不确定 points
数组是否包含任何数据,请使用guard语句以避免强制展开:
You can map values to find the min and max in x and y coordinates like below. If you're not sure if points
array contains any data, use guard statement to avoid force unwrapping:
let xArray = points.map(\.x)
let yArray = points.map(\.y)
guard let minX = xArray.min(),
let maxX = xArray.max(),
let minY = yArray.min(),
let maxY = yArray.max() else { return }
然后从那里:
let minPoint = CGPoint(x: minX, y: minY)
let maxPoint = CGPoint(x: minY, y: minY)
然后您可以修改扩展函数,因为您已经知道哪些值是最小值和最大值:
then you can modify your extension function because you already know which values are min and max:
extension CGRect {
init(minPoint: CGPoint, maxPoint: CGPoint) {
self.init(x: minPoint.x,
y: minPoint.y,
width: maxPoint.x - minPoint.x,
height: maxPoint.y - minPoint.y)
}
}
正如Leo Dabus在下面的评论中建议的那样,您可以在失效的初始化程序扩展中一次性完成所有操作:
As Leo Dabus suggested in the comment below, you can do it all in one go inside failable initializer extension:
extension CGRect {
init?(points: [CGPoint]) {
let xArray = points.map(\.x)
let yArray = points.map(\.y)
if let minX = xArray.min(),
let maxX = xArray.max(),
let minY = yArray.min(),
let maxY = yArray.max() {
self.init(x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY)
} else {
return nil
}
}
}
这篇关于从CGPoints数组获取最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!