在阅读Swift的文档时,Apple通常使用functionName(_:name:)或类似的东西.这个模式究竟是什么,有时候_:_:,有时只是_:,和_:name:.我认为它与参数简写有关,但我不确定,也无法在Swift的编程指南中找到解释.谢谢!
例:
insert(_:atIndex:)
Run Code Online (Sandbox Code Playgroud)
Luc*_*ugh 10
下划线表示该函数没有外部参数名称.Apple的Swift Documentation在您编写自己的函数时谈到了这个概念.
以您编写此函数的情况为例(来自文档):
func sayHello(to person: String, and anotherPerson: String) -> String { ... }
Run Code Online (Sandbox Code Playgroud)
如果您要使用该功能,您可以编写以下内容:
sayHello(to: "Bill", and: "Ted")
Run Code Online (Sandbox Code Playgroud)
这个签名就是sayHello(to:and:).但是,如果我们想要使用该函数sayHello("Bill", "Ted")呢?我们如何表明我们不想要外部参数名称?那就是下划线的来源.我们可以将函数重写为:
func sayHello(person: String, _ anotherPerson: String) -> String { ... }
Run Code Online (Sandbox Code Playgroud)
注意第一个参数不需要_,但后续的参数将是.第一个被推断为没有参数名称.这使得此调用的方法签名sayHello(_:_:)因为您作为调用者没有命名参数.
更新Swift 3.0:
Swift 3.0平等对待所有参数.第一个参数现在需要一个下划线来表示外部参数名称的缺失.在上面sayHello("Bill", "Ted")的调用站点示例中,您必须使用相应的函数或方法声明
func sayHello(_ person: String, _ anotherPerson: String) -> String { ... }
Run Code Online (Sandbox Code Playgroud)
请注意在内部参数名称"person"之前添加下划线.