问题描述
当我在swift中学习Core Graphics时,我在YouTube上观看的教程使用 CGRectMake
函数代替 CGRect
创建一个 CGRect
实例。
When I was learning about Core Graphics in swift, the tutorials that I watched on youtube use the CGRectMake
function instead of the initializer of CGRect
to create a CGRect
instance.
这对我来说很奇怪。我不明白为什么我应该使用前者,因为参数是相同的,我认为使用 XXXMake
函数没有性能优势。
This is so weird to me. I don't understand why should I use the former because the parameters are the same and I think there is no performance benefit to using the XXXMake
function.
此外,为什么swift甚至有一个Make函数,当 CGRect
已经有一个初始化器具有完全相同的参数?我认为模块的开发人员使用一定的设计模式,我不知道。他们使用一个吗?如果是,是什么?我真的想知道一些更多的设计模式。
Also, why does swift even have such a "Make" function, when CGRect
already has an initializer with exactly the same parameters? I think the developers of the modules is using a certain design pattern that I don't know. Did they use one? If yes, what is it? I really want to know some more design patterns.
推荐答案
> CGRectMake 不是由Swift提供。
Short answer: CGRectMake
is not "provided by Swift". The corresponding C function in the CoreGraphicsframework is automatically imported and therefore available in Swift.
更长的答案:
在CoreGraphics
框架中的相应C函数是自动导入的,因此可在Swift中使用。 是定义在
CGGeometry.h从CoreGraphics框架为
Longer answer:CGRectMake is defined in"CGGeometry.h" from the CoreGraphics framework as
CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = width; rect.size.height = height;
return rect;
}
在(Objective-)C中,该函数提供了一个方便的方式
initialize a CGRect
变量:
CGRect r = CGRectMake(x, y, h, w);
Swift编译器会自动从
Foundation中导入所有函数头文件(如果它们是Swift兼容的),所以这个
导入为
The Swift compiler automatically imports all functions from theFoundation header files (if they are Swift-compatible), so thisis imported as
public func CGRectMake(x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect
您可以使用那个或Swift初始化器之一
You can either use that one, or one of the Swift initializers
public init(origin: CGPoint, size: CGSize)
public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat)
public init(x: Double, y: Double, width: Double, height: Double)
public init(x: Int, y: Int, width: Int, height: Int)
我不认为它会造成任何性能差异。许多人可能会
使用 CGRectMake()
,因为他们习惯了它从旧的pre swift
次。 Swift初始化程序更为快速,并且用
显式参数标签更具表现力:
I don't think that it makes any performance difference. Many people mightuse CGRectMake()
because they are used to it from the old pre-Swifttimes. The Swift initializers are more "swifty" and more expressive withthe explicit argument labels:
let rect = CGRect(x: x, y: x, width: w, height: h)
b $ b
更新:自 Swift 3 / Xcode 8 起,CGRectMake
不再是
在Swift中可用。
Update: As of Swift 3/Xcode 8, CGRectMake
is no longeravailable in Swift.
这篇关于为什么swift提供了CGRect初始化程序和CGRectMake函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!