user678392 user678392 - 7 months ago 14
Swift Question

What is the difference between Local and External Parameter Names in Swift

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


I'm confused why the init functions have (fromFahrenheit fahrenheit: Double) and (fromFahrenheit fahrenheit: Double). The docs say:


"The first initializer has a single initialization parameter with an external name of from Fahrenheit and a local name of fahrenheit. The second initializer has a single initialization parameter with an external name of from Kelvin and a local name of kelvin."


Why do we need so many names?

Answer
  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
    

    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.

Comments