swift - 关于调用时和方法内使用方法参数名称的 Doc 声明

标签 swift parameters

在 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: () -> ()) {
        // ...
}

从外部,您将使用参数名称 toFileNamewithCompletionHandler 调用该函数。

self.writeData(data, toFileName: "FileName.txt", withCompletionHandler: nil)

但是,在定义文件写入行为的函数本身内部,您将需要访问变量名为 datafileName 的参数completionHandler.

func writeData( ... ) {
    let successful = SomeFileWriter.writeData(data, fileName: fileName)

    if successful == true {
        completionHandler()
    }
}

如果您希望外部和内部参数名称相同,您可以在参数名称前显式使用井号:

func writeData(#data: NSData, #fileName: String, #completionHandler: () -> ()) {

}

但是您不需要这样做。如果您不提供外部参数名称,Swift 会假定内部和外部参数名称相同。

关于swift - 关于调用时和方法内使用方法参数名称的 Doc 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30022060/

相关文章:

ios - didSelectItemAtIndexPath 修改 UICollectionView 中的多个单元格

c# - 收到空错误 "Unhandled Exception: System.NullException: Value cannot be null"C#

windows - 将具有特殊字符的参数从一个批处理文件发送到另一个批处理文件

javascript - 如何附加事件 "ondblclick",其直接分配的处理程序将 "this"作为参数

c# - Request.QueryString[] 对比 Request.Query.Get() 对比 HttpUtility.ParseQueryString()

swift - 哪个更有效 : Creating a "var" and re-using it, 或创建多个 "let"s?

ios - 临时分发 Swift iOS 应用程序

c++ - 将数组/指针作为模板参数传递

arrays - 将字符串与字符串数组进行比较并计算 Swift 中的匹配项

javascript - 从 swift 或 objective-c 向 js 发送事件