swiftmacoscgpointnspoint

Converting NSPoint to CGPoint using NSPointToCGPoint


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.


Solution

  • 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