SLN
SLN

Reputation: 5082

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.

Upvotes: 2

Views: 371

Answers (2)

Sulthan
Sulthan

Reputation: 130092

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: 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.

Upvotes: 3

mgamba
mgamba

Reputation: 1199

According to the swift documentation,

The use of external parameter names can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent.

for example,

func sayHello(to person: String, and anotherPerson: String) -> String {
    return "Hello \(person) and \(anotherPerson)!"
}

print(sayHello(to: "Bill", and: "Ted"))

Upvotes: 6

Related Questions