简体   繁体   English

Swift相当于静态Objective-C表达式

[英]Swift equivalent of static Objective-C expression

What is the Swift equivalent of the following expression: 什么是以下表达式的Swift等价物:

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; 你的代码是普通的C; there's no Objective-C involved. 没有涉及Objective-C。 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). 它是没有符号发出的函数的定义(这是static在这种情况下的作用)。 So the function is only visible in the current compilation unit (the .c or .m file where it's defined). 因此该函数仅在当前编译单元(定义它的.c或.m文件)中可见。 The function is not tied to some class. 该功能与某些类无关。

The semantic Swift equivalent would be a plain swift function with the private access modifier. 语义Swift等价物将是具有private访问修饰符的普通快速函数。

For this type of function (utility) I would recommend using the struct extension, but there are three ways. 对于这种类型的函数(实用程序),我建议使用struct扩展,但有三种方法。

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 : 如果你的方法属于一个类,在Swiftyou中可以使用type方法

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. 您可以通过在方法的func关键字之前编写关键字class来指示类的类型方法,并通过在方法的func关键字之前编写关键字static来指示结构和枚举的类型方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM