关于调用时和方法内使用方法参数名称的 Doc 声明
Doc statement about use of method parameter names when called and within the method
在 Apple 关于 Swift 的书中,我找到了这段摘录:
Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.
我完全不知道这是什么意思。他们给出的例子没有说明任何问题。有人可以给我举个例子吗? (也许明确显示摘录中提到的差异。)
在Swift中,您可以定义一个函数,其参数在外部调用时具有一个名称,但在函数定义中将它们用作变量时使用另一个名称。这使您的代码更具可读性,就像一个英文句子而不是代码。
例如,你可以定义一个写文件函数如下:
func writeData(data: NSData,
toFileName fileName: String,
withCompletionHandler completionHandler: () -> ()) {
// ...
}
从外部,您将使用参数名称 toFileName
和 withCompletionHandler
.
调用该函数
self.writeData(data, toFileName: "FileName.txt", withCompletionHandler: nil)
但是,在定义文件写入行为的函数内部,您需要访问变量名为 data
、fileName
和 completionHandler
的参数。
func writeData( ... ) {
let successful = SomeFileWriter.writeData(data, fileName: fileName)
if successful == true {
completionHandler()
}
}
如果您希望外部和内部参数名称相同,您可以在参数名称前显式使用井号:
func writeData(#data: NSData, #fileName: String, #completionHandler: () -> ()) {
}
但你不需要这样做。如果您不提供外部参数名称,Swift 假定内部和外部参数名称相同。
在 Apple 关于 Swift 的书中,我找到了这段摘录:
Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.
我完全不知道这是什么意思。他们给出的例子没有说明任何问题。有人可以给我举个例子吗? (也许明确显示摘录中提到的差异。)
在Swift中,您可以定义一个函数,其参数在外部调用时具有一个名称,但在函数定义中将它们用作变量时使用另一个名称。这使您的代码更具可读性,就像一个英文句子而不是代码。
例如,你可以定义一个写文件函数如下:
func writeData(data: NSData,
toFileName fileName: String,
withCompletionHandler completionHandler: () -> ()) {
// ...
}
从外部,您将使用参数名称 toFileName
和 withCompletionHandler
.
self.writeData(data, toFileName: "FileName.txt", withCompletionHandler: nil)
但是,在定义文件写入行为的函数内部,您需要访问变量名为 data
、fileName
和 completionHandler
的参数。
func writeData( ... ) {
let successful = SomeFileWriter.writeData(data, fileName: fileName)
if successful == true {
completionHandler()
}
}
如果您希望外部和内部参数名称相同,您可以在参数名称前显式使用井号:
func writeData(#data: NSData, #fileName: String, #completionHandler: () -> ()) {
}
但你不需要这样做。如果您不提供外部参数名称,Swift 假定内部和外部参数名称相同。