奇怪的代码如下
func sayHello2(name : String){
println("Hello! \(name)")
}
sayHello2(name : "andy") // Error ->Playground execution failed: <EXPR>:25:10: error:
extraneous argument label 'name:' in call
sayHello6(name : "andy")
sayHello2("andy") // No Error -> Hello! andy
func sayHello3(name : String = "world"){
println("Hello! \(name)")
}
sayHello6(name : "andy") // No Error -> Hello! andy
sayHello6("andy") //Error -> Playground execution failed: <EXPR>:31:11: error: missing
argument label 'name:' in call
sayHello2("Choi")
两个来源是矛盾的。
你们能解释一下吗?
最佳答案
发生这种情况是因为:
Swift provides an automatic external name for any parameter that has a default value. The automatic external name is the same as the local name, as if you had written a hash symbol before the local name in your code.
摘自 External Names for Parameters with Default Values
通常一个函数(请注意,一个全局函数而不是一个类/结构方法)不会为其参数自动生成外部名称(但您可以手动指定它们)。如果参数具有默认值,swift 会自动使用本地名称作为外部名称(除非您提供自己的名称)。如果您不希望这种情况发生,只需在参数前加上下划线:
func sayHello3(_ name : String = "world") {
至于类/结构方法,Swift 自动为所有方法参数提供一个外部名称,但第一个除外。同样,您可以自由地通过为第一个参数明确指定外部名称来更改它,和/或通过使用下划线作为前缀来禁用所有其他参数的外部名称。
关于Swift func参数奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452542/