Reputation: 1389
Weird code as follow
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")
Two source is contradiction.
Can you guys explain?
Upvotes: 0
Views: 235
Reputation: 72760
That happens because:
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.
Excerpt from External Names for Parameters with Default Values
Normally a function (and note, a global function and not a class/struct method) doesn't auto-generate external names for its parameters (but you can manually specify them). In case of parameters with default values, swift automatically uses the local name as the external name (unless you provide your own). If you don't want that to happen, just prefix the parameter with an underscore:
func sayHello3(_ name : String = "world") {
As for class/struct methods, Swift automatically provide an external name for all method parameters but the first. Again, you have freedom to change that by explicitly specifying an external name for the first parameter, and/or disable the external name for all other parameters by prefixing with an underscore.
Upvotes: 2