Adding external parameter names

In the preceding examples in this section, we defined the parameters' names and value types in the same way we would define parameters in C code. In Swift, we are not limited to this syntax as we can also use external parameter names.

External parameter names are used to indicate the purpose of each parameter when we call a function. An external parameter name for each parameter needs to be defined in conjunction with its local parameter name. The external parameter name is added before the local parameter name in the function definition. The external and local parameter names are separated by a space.

Let's look at how to use external parameter names. But before we do, let's review how we have previously defined functions. In the following two examples, we will define a function without external parameter names, and then redefine it with external parameter names:

func winPercentage(team: String, wins: Int, loses: Int) -> Double{  
  return Double(wins) / Double(wins + loses) 
} 

In the preceding example, the winPercentage() function accepted three parameters. These parameters were team, wins, and loses. The team parameter should be of type String and the wins and loses parameters should be of type int. The following line of code shows how to call the winPercentage() function:

var per = winPercentage(team: "Red Sox", wins: 99, loses: 63) 

Now, let's define the same function with external parameter names:

func winPercentage(baseballTeam team: String, withWins wins: Int, andLoses losses: Int) -> Double { 
  return Double(wins) / Double(wins + losses) 
} 

In the preceding example, we redefined the winPercentage() function with external parameter names. In this redefinition, we have the same three parameters: team, wins, and losses. The difference is how we define the parameters. When using external parameters, we define each parameter with both an external parameter name and a local parameter name separated by a space. In the preceding example, the first parameter had an external parameter name of baseballTeam and an internal parameter name of team.

When we call a function with external parameter names, we need to include the external parameter names in the function call. The following code shows how to call this function:

var per = winPercentage(baseballTeam:"Red Sox", withWins:99,
andLoses:63)

While using external parameter names requires more typing, it does make your code easier to read. In the preceding example, it is easy to see that the function is looking for the name of a baseball team, the second parameter is the number of wins, and the last parameter is the number of losses.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset