Is there any shorthand way to write CGPoint, CGRec

2019-05-25 20:14发布

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?

标签: swift swift3
2条回答
做个烂人
2楼-- · 2019-05-25 20:17

You could extend CGPoint to ExpressibleByArrayLiteral protocol, then you could use an array literal to initialize an CGPoint:

view.center = [10, 20]

the code:

extension CGPoint: ExpressibleByArrayLiteral {
    public init(arrayLiteral elements: CGFloat...) {
        assert(elements.count == 2)
        self.init(x: elements[0], y: elements[1])
    }
}

You should handle the element count of the array well, because complier won't check it for you. Even though this method breaks the compile safety, it's a very convenient method to use.

There is already a lib (Literal) implement this for you. It have handled some fall-down situations, like pass a one-element array to a variable where CGPoint required.

查看更多
可以哭但决不认输i
3楼-- · 2019-05-25 20:30

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

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
查看更多
登录 后发表回答