Swift错误:缺少参数标签'名称:'在电话中

时间:2014-06-04 23:29:09

标签: swift

我正在学习默认参数,并且搁浅了一些奇怪的东西:

import UIKit

func greet(name: String = "world") {
    println("hello \(name)")
}

greet("jiaaro")

这会引发错误:

Playground execution failed: error: <REPL>:9:7: error: missing argument label 'name:' in call
greet("jiaaro")
      ^
      name:

我理解它需要greet(name: "jiaaro"),但我

3 个答案:

答案 0 :(得分:12)

Swift函数可以指定本地和外部参数名称:

func greet(who name: String = "world") {
    println("hello \(name)")
}

// prints "hello world"
greet()

// prints "hello jiaaro"
greet(who:"jiaaro")

// error
greet("jiaaro")

// error
greet(name: "jiaaro")

要退出此行为,您可以使用下划线作为外部名称。请注意,第一个参数隐式使用“无外部名称”行为:

func greet(name: String = "world", _ hello: String = "hello") {
    println("\(hello) \(name)")
}

// prints "hello world"
greet()

// prints "hello jiaaro"
greet("jiaaro")

// prints "hi jiaaro"
greet("jiaaro", "hi")

// error
greet(name: "jiaaro")
  

现在Swift 2.0中不允许使用以下内容,请参阅下面的等效代码。

您可以使用#前缀为第一个参数使用相同的本地和外部名称:

func greet(#name: String = "world", hello: String = "hello") {
    println("\(hello) \(name)")
}

// prints "hi jiaaro"
greet(name: "jiaaro", hello: "hi")
  

Swift 2.0代码:

func greet(name name: String = "world", hello: String = "hello") {
    println("\(hello) \(name)")
}

// prints "hi jiaaro"
greet(name: "jiaaro", hello: "hi")

答案 1 :(得分:3)

Swift默认需要参数标签,因为它支持具有多个初始值设定项的类。参数标签的好处来自Swift推断使用哪个初始化器的能力;不仅是参数类型,还有参数名称。

struct Celsius {
    var temperatureInCelsius: Double = 0.0

    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }

    init(fromKelvin kelvin: Double) {
        temperatureInCelsius = kelvin - 273.15
    }
}

let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0

let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0

有关详情,请参阅此页:https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_272

答案 2 :(得分:1)

我只是想添加你现在的代码

func greet(name: String = "world") {
    print("hello \(name)")
}

greet("jiaaro")

在xcode中工作正常,我只是用“print”

更改了“println”