Reputation: 2942
I got error: '(Int, Int)' is not identical to 'CGPoint'
How to convert a (Int, Int) to CGPoint
let zigzag = [(100,100),
(100,150),(150,150),
(150,200)]
override func drawRect(rect: CGRect)
{
// Get the drawing context.
let context = UIGraphicsGetCurrentContext()
// Create the shape (a vertical line) in the context.
CGContextBeginPath(context)
//Error is here
CGContextAddLines(context, zigzag, zigzag.count)
// Configure the drawing environment.
CGContextSetStrokeColorWithColor(context,UIColor.redColor().CGColor)
// Request the system to draw.
CGContextStrokePath(context)
}
Upvotes: 1
Views: 1006
Reputation: 539815
CGContextAddLines()
expects an array of CGPoint
. If you already have an
array of (Int, Int)
tuples then you can convert it with
let points = zigzag.map { CGPoint(x: $0.0, y: $0.1) }
Upvotes: 3
Reputation: 51911
Yet another:
func CGPoints(points:(x:CGFloat, y:CGFloat)...) -> [CGPoint] {
return map(points) { CGPoint($0) }
}
let zigzag = CGPoints(
(100,100),(100,150),(150,150),(150,200)
)
Upvotes: 0
Reputation: 72760
An alternate way to avoid the boilerplate code required to create instances of the same type is to make CGPoint
implement the ArrayLiteralConvertible
, making it initializable by assigning an array of CGFloat
:
extension CGPoint : ArrayLiteralConvertible {
public init(arrayLiteral elements: CGFloat...) {
self.x = elements.count > 0 ? elements[0] : 0.0
self.y = elements.count > 1 ? elements[1] : 0.0
}
}
and then use it as follows:
let zigzag:[CGPoint] = [
[100,100],
[100,150],
[150,150],
[150,200]
]
A few notes:
CGPoint
is initialized with x = 0
and y = 0
y = 0
Upvotes: 2
Reputation: 18995
If it tells you to use CGPoint, use it! Just (number,number) is a pair of int
s.
let zigzag = [CGPointMake(100,100),
CGPointMake(100,150),CGPointMake(150,150),
CGPointMake(150,200)]
Upvotes: 1