I am new on Swift, my question is where do we use and need External Parameter?
From the Apple's Swift Language Guide:
Sometimes it’s useful to name each parameter when you call a function, to indicate the purpose of each argument you pass to the function.
If you want users of your function to provide parameter names when they call your function, define an external parameter name for each parameter, in addition to the local parameter name.
So, you don't "need" an external parameter name but it is a good practice to use them because they serve as documentation about the parameters at the point the method is called.
For example, without using external parameter names, you can define a join method like this:
func join(_ s1: String,_ s2: String,_ joiner: String) -> String {
return s1 + joiner + s2
}
which will then be called like this:
join("foo", "bar", ", ")
As you can see, each parameter's meaning is not very clear. Using external parameter names, you could define the same method like below:
func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String {
return s1 + joiner + s2
}
which would then force the users to call it like this:
join(string: "foo", toString: "bar", withJoiner: ", ")
You can see that it makes the meaning of the parameters, along with what the method does, much more clear.
It might seem not so important in this simple example but when defining methods that take a lot of parameters with not-so-obvious meanings, using external parameter names will make your code much more easy to understand.
Update for Swift 3:
This has become even more meaningful with the introduction of Swift 3. Consider the append(contentsOf:)
method of the Array class in Swift 3:
Not having different internal and external parameter names in this case would force us to change the label contentsOf
to something like string
in the call site, which wouldn't read as good as the former one. Swift 3 API guidelines rely on having different internal and external parameter names to create clear and concise methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With