Swift func参数奇怪

标签 swift parameters func

奇怪的代码如下

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/

相关文章:

swift - 如何在触摸屏幕时移动 Sprite 并在点击屏幕时禁用

ios - Popover 适用于 iOS 8 但不适用于 iOS 7

asp.net - Oracle中Link DB参数问题

C 编程 - 返回无法正常工作

swift - 如何在 Alamofire 中正确提供参数

ios - 使用 retryWhen 根据 http 错误代码更新 token

php - 是否可以对具有串联变量的查询进行参数化?

c# - Func 委托(delegate)不链接方法

swift - 如何在 Swift 中为成员函数设置结构成员

c# - 如何通过 ConverterParameter 将 TimeSpan.FromSeconds 传递给转换器?