SLN SLN - 5 months ago 9
Swift Question

What is the benefits of external names for swift function?

I kind of knowing what is a external names in a function. But I cannot give out a precise, clear and convincing answer for the question: What is the purpose of of the external names, when to use it and what is the benefits of using it.

func RandomInt(minimum min: Int, maximum max: Int) -> Int {
if max < min { return min }
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}


My understanding
In the code above,
minimum
and
maximum
are the external names. They are "binding" to the internal names (
min
and
max
). When you calling the function, the external names should write into the argument list. This long and descriptive external name improves code readability when you using the function.

Please correct my understandings if anything is wrong or add more if needed

Thanks a lot.

Answer

The external parameters were needed mainly for compatibility with Obj-C methods because Obj-C is using them too (although they are named differently), however they are also helping readability in method caller context.

Note that external parameters are actually a part of the method name therefore you can overload methods by changing the external parameter.

Another interesting point of named parameters is the ability to provide default values:

func test(x x: Int = 0, y: Int = 1, z: Int = 2) {
    print("x: \(x), y: \(y), z: \(z)")
}

// we can skip a parameter in the middle!
test(x: 10, z: 5)

By the way, named parameters are common in many programming languages (see a list on wikipedia). Every language implements them slightly differently though.

Comments