问题描述
函数定义中的下划线是什么意思?
What does the lone underscore mean in function definitions?
例如map(_:)
我知道在定义函数时我可以:
I understand that when defining functions I can do:
func myFunc(_ string: String) { ... }
我会不会将其称为 myFunc(_:)
而不是 myFunc(_string:)
,即故意隐藏参数名称?
Would I then refer to that as myFunc(_:)
instead of myFunc(_string:)
, i.e. purposefully hiding the parameter name?
推荐答案
_
用于定义参数未命名
如果你有多个 _
它表明你不需要在函数调用中命名参数
If you have multiple _
it states that you do not need to name the parameters in your function call
func myFunc(name:String, _ age:String){
}
myFunc("Milo", "I'm a really old wizard")
如果你不使用下划线,你会使用
If you do not use the underscore you would use
myFunc("Milo", age: "I'm a really old wizard")
_
不是函数调用所必需的.它只是用来表示不需要名字的东西.
The _
is not necessary for function calls. It is just used to indicate that something does not need to have a name.
关于如何引用您的函数,您不必为函数调用传递任何名称.
但是由于你也没有定义参数类型,这在我看来就像一个无效的例子(它至少在 Swift 2.0 的 Xcode 7 中不起作用)
In regards to how you would refer to your function, You would not have to pass any name for the function call.
But since you also don’t define a parameter type this seems to me like an invalid example (it at least doesn’t work in Xcode 7 with Swift 2.0)
从 Swift 3.0 开始
Since Swift 3.0
myFunc(name: "Milo", age: "I'm a really old wizard")
应该使用
这篇关于什么是 _: 在 Swift 中告诉我的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!