CGPoint、CGRect等有什么简写的方法吗? [英] Is there any shorthand way to write CGPoint, CGRect, etc?
本文介绍了CGPoint、CGRect等有什么简写的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Swift 3.0 中,我们现在像这样声明 CGPoints:
With Swift 3.0, we now declare CGPoints like so:
CGPoint(x: 1.0, y: 0.0)
这是,呃...有点冗长.当你编写一个以 CGPoint 作为参数的函数时,事情会很快变得丑陋:
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))
像 CGPoint 和 CGRect 这样的结构有简写吗?
Is there any shorthand for structs like CGPoint and CGRect?
推荐答案
正如评论中已经建议的那样,您可以创建自己的扩展.
As already suggested in the comments you can create your own extension.
您可以添加一个接受 2 个 CGFloat(s)
并且不需要外部参数名称的初始化程序
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
这篇关于CGPoint、CGRect等有什么简写的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文