How to convert CGPoint in NSValue in swift?
Asked Answered
N

5

20

As my question title says how can I convert CGPoint into NSValues so I can store then Into array In swift.

In objective-C we can do it like this:

  // CGPoint converted to NSValue
     CGPoint point = CGPointMake(9, 9);
     NSValue *pointObj = [NSValue valueWithCGPoint:point];

But can anybody tell me that how can I do this in swift?

Thanks In Advance.

Nynorsk answered 8/10, 2014 at 7:46 Comment(1)
Good question :)Microtone
P
38

Try something like that:

let point = CGPointMake(9, 9)
var pointObj = NSValue(CGPoint: point)
Pandybat answered 8/10, 2014 at 8:12 Comment(1)
idk why there is no popup for this c-torJura
A
12

Exactly as you'd imagine:

let point = CGPoint(x: 9.0, y: 9.0)
let pointObj = NSValue(CGPoint: point)
let newPoint = pointObj.CGPointValue()
Arbitration answered 8/10, 2014 at 8:14 Comment(0)
J
7

If you aren't planning on using the array in Objective-C, and can keep it as a Swift Array, then you don't need to turn the point into an NSValue, you can just add the point to the array directly:

let point1 = CGPoint(x: 9.0, y: 9.0)
let point2 = CGPoint(x: 10.0, y: 10.0)

let pointArray = [point1, point2] // pointArray is inferred to be of type [CGPoint]

let valuesArray = pointsArray as [NSValue]
Jetsam answered 1/1, 2015 at 12:16 Comment(1)
But if that was the case, you would be using NSPoint, not CGPoint. It's obvious it's for interop, so your answer is irrelevant for the question.Atomicity
P
1

swift 3

let pointObj =  NSValue(cgPoint: CGPoint(x:9, y:9))

https://developer.apple.com/reference/foundation/nsvalue/1624531-init

Photocompose answered 14/8, 2016 at 23:13 Comment(4)
Ok. A few things. pointObj is an odd name for a NSValue. The .init is not required. The parameter you are passing in is a CGSize not a CGPoint. This makes the name even more odd.Flyleaf
Using .init is wrong/discouraged in Swift in general.Atomicity
thx. the pointObj was regarded to the accepted answer to be consistent for better reading. I am going to edit that.Photocompose
This is very strange but it does not exist in macOS, it is simply 'point'Hippolytus
T
1

swift 4

let point = NSValue.init(cgPoint: mask.position)
Texture answered 31/1, 2018 at 6:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.