Swift 中的本地参数名和外部参数名有什么区别?

5

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID203

struct Celsius {
    var temperatureInCelsius: Double
    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

我对为什么init函数有(fromFahrenheit fahrenheit: Double)和(fromKelvin kelvin: Double)感到困惑。文档说:

"第一个初始化器有一个名为from Fahrenheit的外部名称和一个名为fahrenheit的本地名称。第二个初始化器有一个名为from Kelvin的外部名称和一个名为kelvin的本地名称。"

为什么我们需要这么多名称呢?


3
我刚刚写了一个覆盖这个问题的 Swift 教程,可能会对你有帮助!内部参数名称:http://www.apeth.com/swiftBook/ch02.html#_function_parameters_and_return_value 外部参数名称:http://www.apeth.com/swiftBook/ch02.html#_external_parameter_names - matt
2个回答

5
  1. This is used for an easy interface with Objective C. Objective C methods have both named local parameters and external parameters.

    For example this is a typical Objective C method.

    -(void)setValue:(NSObject *)object forKey:(NSObject *)key
    

    This will be called as [dict setValue:object1 forKey:object2]

    The same function in swift will be called as

    dict.setValue(object1,forKey:object2)
    
  2. It also clarifies the purpose of each parameter and helps in distinguishing functions with similar names and different parameters. Functions can also have same signature with different external names.

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

    In your example, both functions take a Double. Without external parameters there will be no way to distinguish them when called.


2

在方法中使用本地参数,而在调用方法时使用外部参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接