GoldenJoe GoldenJoe - 9 months ago 35
Swift Question

Is there any shorthand way to write CGPoint, CGRect, etc?

With Swift 3.0, we now declare CGPoints like so:

CGPoint(x: 1.0, y: 0.0)

This is, uh...kinda verbose. When you write a function that takes a CGPoint as an argument, things get ugly pretty fast:

myObject.callMyFunc(someVar: 1, point1: CGPoint(x: 1.0, y: 0.0), point2: CGPoint(x: 1.0, y: 2.0))

Is there any shorthand for structs like CGPoint and CGRect?


As already suggested in the comments you can create your own extension.


You can add an initializer that accepts 2 CGFloat(s) and doesn't require external param names

extension CGPoint {
    init(_ x: CGFloat, _ y: CGFloat) {
        self.x = x
        self.y = y

let point = CGPoint(1, 2)

Infix Operator

You can also define your infix operator

infix operator ° {}
func °(x: CGFloat, y: CGFloat) -> CGPoint {
    return CGPoint(x: x, y: y)

let point = 1.1 ° 1.1