What is the Swift equivalent of the following expression:
static CGRect MYScaleRect(CGRect rect, CGFloat scale)
{
return CGRectMake(rect.origin.x * scale, rect.origin.y * scale, rect.size.width * scale, rect.size.height * scale);
}
What is the Swift equivalent of the following expression:
static CGRect MYScaleRect(CGRect rect, CGFloat scale)
{
return CGRectMake(rect.origin.x * scale, rect.origin.y * scale, rect.size.width * scale, rect.size.height * scale);
}
Your code is plain C; there's no Objective-C involved. Also, strictly speaking, it is not an expression.
It is the definition of a function for which no symbol is emitted (that's what static
does in this context). So the function is only visible in the current compilation unit (the .c or .m file where it's defined). The function is not tied to some class.
The semantic Swift equivalent would be a plain swift function with the private
access modifier.
For this type of function (utility) I would recommend using the struct extension, but there are three ways.
Free function: (equivalent of the function from the question)
private func MYScaleRect(rect: CGRect , scale: CGFloat ) -> CGRect {
return CGRectMake(rect.origin.x * scale, rect.origin.y * scale, rect.size.width * scale, rect.size.height * scale)
}
Struct extension:
private extension CGRect {
static func MYScaleRect(rect: CGRect , scale: CGFloat ) -> CGRect {
return CGRectMake(rect.origin.x * scale, rect.origin.y * scale, rect.size.width * scale, rect.size.height * scale)
}
}
Class method:
private class func MYScaleRect(rect: CGRect , scale: CGFloat ) -> CGRect {
return CGRectMake(rect.origin.x * scale, rect.origin.y * scale, rect.size.width * scale, rect.size.height * scale)
}
For this type of function (utility) I would recommend using the extension.
If your method belongs to a class, in Swiftyou can use type method:
class func MYScaleRect(rect: CGRect , scale: CGFloat )-> CGRect {}
Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods for classes by writing the keyword class before the method’s func keyword, and type methods for structures and enumerations by writing the keyword static before the method’s func keyword.