Reputation: 1976
Please forgive this naive question, but is there any direct way to create a cgpoints from a coordinate pair without extracting the x and y value separately.
I know you can do:
CGPoint point = CGPointMake(2, 3);
or
float x = 2;
float y = 3;
CGPoint p = CGPointMake(x,y);
Is there any way to create it a point directly from (2,3) without extracting each x and y separately?
The reason I'm asking is I have to create a lot of CGPoints from an array of coordinates that look like [(2,3),(4,5),(6,7)]
etc.
Thanks in advance for any suggestions.
Upvotes: 1
Views: 160
Reputation: 84
A solution for Objective C might look like this:
CGFloat pointValues[] = {
2, 3,
4, 5,
6, 7
};
for(int i = 0; i < sizeof(pointValues) / sizeof(CGFloat); i += 2) {
CGPoint p = CGPointMake(pointValues[i], pointValues[i + 1]);
// Do something with 'p'...
}
The pointValues
array is a 1D array of the x and y values of each point.
Alternatively, if you can use Objective C++, you can simply do this:
CGPoint points[] {
{ 2, 3 },
{ 4, 5 },
{ 6, 7 }
};
Upvotes: 0
Reputation: 16371
Use map
and CGPoint
init with x
and y
parameters.
let coordinates = [(2,3),(4,5),(6,7)]
let points = coordinates.map { CGPoint(x: $0, y: $1) }
print("\(type(of: points)): \(points)") // You'll get an `[CGPoint]` although they print as normal [(x, y)] tuples array.
Upvotes: 3
Reputation: 236538
Swift can infer the proper initializer if you map an array of tuples of the same types of an available initializer of the resulting type:
let points = [(2,3),(4,5),(6,7)].map(CGPoint.init)
Upvotes: 1
Reputation: 3018
Well, if you have a flair for the dramatic, maybe something like this
// One big array
float * p1 = ( float [] ){ 1, 2, 3, 4, 5, 6, 7, 8 };
float * end1 = p1 + 8;
while ( p1 < end1 )
{
CGPoint point = CGPointMake ( * p1, * ( p1 + 1 ) );
p1 += 2;
NSLog ( @"Point ( %f, %f )", point.x, point.y );
}
// Array of 2D tuples
// Not much difference though, maybe easier on the eyes?
float * p2 = ( float * )( float [][ 2 ] ){ { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
float * end2 = p2 + 8;
while ( p2 < end2 )
{
CGPoint point = CGPointMake( * p2, * ( p2 + 1 ) );
p2 += 2;
NSLog ( @"Point ( %f, %f )", point.x, point.y );
}
Upvotes: 0