Converting NSPoint to CGPoint using NSPointToCGPoint

600 views Asked by At

How difficult can it be to access x and y coordinates from NSPoint...Can't believe it.

I get an NSPoint from following call:

var mouseLoc = [NSEvent .mouseLocation]

I need to access x and y coordinates. NSPoint does not offer a getter like CGPoint. I learned: I have to cast into CGPoint but nothing that I found seems to work in latest Swift anymore:

var p = (CGPoint)mouseLoc // error: Cannot convert value of type '[NSPoint]' (aka 'Array<CGPoint>') to expected argument type 'NSPoint' (aka 'CGPoint')

var p = NSPointToCGPoint(mouseLoc) // error: Cannot convert value of type '[NSPoint]' (aka 'Array<CGPoint>') to expected argument type 'NSPoint' (aka 'CGPoint')

I am sure it's a complete beginner thing but I just don't get it.

2

There are 2 answers

0
Martin R On BEST ANSWER

Swift uses a different syntax for calling instance or class methods than Objective-C.

// Objective-C
NSPoint mouseLoc = [NSEvent mouseLocation]

translates to

// Swift
let mouseLoc = NSEvent.mouseLocation

whereas your Swift code creates an array containing a single NSPoint.

Also NSPoint is a type alias for CGPoint:

typealias NSPoint = CGPoint

so you can simply use the same accessors:

// Swift
let mouseLoc = NSEvent.mouseLocation
let xCoord = mouseLoc.x
let yCoord = mouseLoc.y
0
Denis Kozhukhov On

Here seems what mouseLoc is an array of NSEvent. Iterate through it and convert each point individually or use only one (first or last element).

Iterate like this:

let allPoints = mouseLoc.forEach { NSPointToCGPoint($0) }

But in this case you also will get an array, but now of CGPoint. You probably want to use only one of it, first or last.

But also maybe you have an array with only one element - use .first.