lijinma
lijinma

Reputation: 2942

'(Int, Int)' is not identical to 'CGPoint'

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

Answers (4)

Martin R
Martin R

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

rintaro
rintaro

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

Antonio
Antonio

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:

  • stylistically, it doesn't look good - it would be good if literals could be used for tuples, but I am not aware of any way to do that
  • if an empty array is used, the CGPoint is initialized with x = 0 and y = 0
  • if an array with one element is used, it is initialized with y = 0
  • if more than 2 values are used, all the ones after the 2nd are ignored

Upvotes: 2

nicael
nicael

Reputation: 18995

If it tells you to use CGPoint, use it! Just (number,number) is a pair of ints.

let zigzag = [CGPointMake(100,100),
    CGPointMake(100,150),CGPointMake(150,150),
    CGPointMake(150,200)]

Upvotes: 1

Related Questions