从Correct way to find max in an Array in Swift绘图,我试图使用reduce
找到Swift数组中最左边的位置。我原以为这会起作用:
var a = [CGPoint(x:1,y:1),CGPoint(x:2,y:2),CGPoint(x:0,y:0)]
var leftMost = a.reduce(CGPoint(x:CGFloat.max,y:CGFloat.max)) {min($0.x,$1.x)}
然而,我收到此错误:
`Type 'CGPoint' does not conform to protocol 'Comparable'
当然,我不是在比较CGPoint,我正在比较点.x
,它应该是CGFloat
。
想法?
答案 0 :(得分:6)
数组包含CGPoint
,而在reduce闭包中,您尝试返回CGFloat
- 您必须将其转换为CGPoint
而不是:
var leftMost = a.reduce(CGPoint(x:CGFloat.greatestFiniteMagnitude,y:CGFloat.greatestFiniteMagnitude)) {
CGPoint(x: min($0.x,$1.x), y: $0.y)
}.x
我知道,错误信息没有多大帮助:)
实现相同结果的另一种方法是首先将点转换为x坐标,然后减少:
var leftMost = a.map { $0.x }.reduce(CGFloat.greatestFiniteMagnitude) { min($0,$1) }
可能更容易阅读,但在性能方面可能更昂贵。但正如@MartinR建议的那样,它也可以简化为:
var leftMost = a.reduce(CGFloat.greatestFiniteMagnitude) { min($0, $1.x) }
答案 1 :(得分:0)
Swift 5实施:
用法:
enum Position {
case topMost
case bottomMost
case leftMost
case rightMost
}
func findPoint(points: [CGPoint], position: Position) -> CGPoint? {
var result: CGPoint?
switch (position) {
case .bottomMost:
result = points.max { a, b in a.y < b.y }
case .topMost:
result = points.max { a, b in a.y > b.y }
case .leftMost:
result = points.max { a, b in a.x > b.x }
case .rightMost:
result = points.max { a, b in a.x < b.x }
}
return result
}
函数和枚举:
class CashEvent(models.Model):
date = models.DateField()
profit = models.FloatField()
damage = models.FloatField()
seller = models.ForeignKey(Seller)
class Seller(models.Model):
name = models.CharField()
store = models.ForeignKey(Store)
class Store(models.Model):
name = models.CharField()
country = models.ForeignKey(Country)