alitsnr alitsnr - 9 months ago 50
Swift Question

External Parameters in Swift

  • I am new on Swift and studying functions. I have a question about
    External Parameter. Where do we use and need External Parameter?

Answer Source

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 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 parameters, 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, what each parameter means is not very clear. Using external parameters, 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 parameters 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.