Search code examples
swiftreducecgpoint

Correct way to find leftmost position in an Array of CGPoints in Swift


Drawing from Correct way to find max in an Array in Swift, I am attempting to find the leftmost position in Swift array using reduce. I would have thought that this would work:

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)}

However, I get this error:

`Type 'CGPoint' does not conform to protocol 'Comparable'

Of course, I'm not comparing a CGPoint, I'm comparing the point .x, whic should be a CGFloat.

Ideas?


Solution

  • The array holds CGPoint, whereas in the reduce closure you're trying to return a CGFloat - you have to convert it to a CGPoint instead:

    var leftMost = a.reduce(CGPoint(x:CGFloat.greatestFiniteMagnitude,y:CGFloat.greatestFiniteMagnitude)) {
        CGPoint(x: min($0.x,$1.x), y: $0.y)
    }.x
    

    I know, the error message doesn't help much :)

    Another way to achieve the same result is by transforming the points into x coordinates first, and then reduce:

    var leftMost = a.map { $0.x }.reduce(CGFloat.greatestFiniteMagnitude) { min($0,$1) }
    

    maybe easier to read, although probably more expensive in terms of performance. But as @MartinR suggests, it can also be simplified as:

    var leftMost = a.reduce(CGFloat.greatestFiniteMagnitude) { min($0, $1.x) }