Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert CGPoint in NSValue in swift?

Tags:

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.

like image 893
Dharmesh Kheni Avatar asked Oct 08 '14 07:10

Dharmesh Kheni


4 Answers

Try something like that:

let point = CGPointMake(9, 9)
var pointObj = NSValue(CGPoint: point)
like image 198
derdida Avatar answered Oct 20 '22 03:10

derdida


Exactly as you'd imagine:

let point = CGPoint(x: 9.0, y: 9.0)
let pointObj = NSValue(CGPoint: point)
let newPoint = pointObj.CGPointValue()
like image 25
Stephen Darlington Avatar answered Oct 20 '22 01:10

Stephen Darlington


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]
like image 21
Abizern Avatar answered Oct 20 '22 01:10

Abizern


swift 3

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

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

like image 27
Jan Avatar answered Oct 20 '22 01:10

Jan