When coding in Swift, one function that all developers no doubt call generously is print. We use it everywhere every day; Most of the time, this is our path to fast and dirty debugging.

Although print seems to win out among the most commonly used commands in Swift, have you ever wondered how it makes it possible to accept any number of arguments? More importantly, have you thought about implementing our own functionality, like Print?

If so, the answer to all this is simple and has a name; Variable parameter.

A function with variable parameters

A function with mutable arguments is a function that takes arguments that can take zero, one or more of the same type. To indicate that a parameter is mutable, all we have to do is append three points to the parameter’s data type.

It is also very simple to use variable parameter values in the body of a function; Let’s think of it as an array. Take a look at the following example, which shows all of this:

func createSentence(_ words: String...) -> String {
    words.joined(separator: " ")
}
Copy the code

CreateSentence (_:) is a simple function that creates a sentence using a given word as an argument. The sentence can be as short or as long as we want, depending on the number of words provided. Such as:

let sentence = createSentence("Variadic", "parameters", "in", "Swift!" ) print(sentence) // It prints: // Variadic parameters in Swift!Copy the code

The following functionality is similar to the previous one; The only thing that changes is the parameter, this time an array of string values:

func createSentence(_ words: [String]) -> String {
    words.joined(separator: " ")
}
Copy the code

There are two differences in using the above method, namely that it is always compared to the first function with mutable arguments. The first is about the way we pass values to functions; It must be an array, as opposed to the previous example, where values are separated only by commas:

let anotherSentence = createSentence(["Hello", "Swift", "world!"] ) print(anotherSentence) // It prints: // Hello Swift world!Copy the code

The second distinction has already been mentioned; This is a function with variable arguments that can take zero arguments. The following is entirely true because the mutable argument allows this:

let empty = createSentence()
Copy the code

Empty will be an empty string in this case. In the second function, we can still avoid providing any values; However, an empty array must still be passed:

let anotherEmpty = createSentence([])
Copy the code

Here is a different example of a function with mutable arguments:

func averageTemperature(_ temperatures: Double...) -> Double { ! temperatures.isEmpty ? temperatures.reduce(0, { $0 + $1 }) / Double(temperatures.count) : 0 }Copy the code

What you do above is you compute the average temperature for all the parameters given. Since temperatures are a variable parameter, we can provide any number of temperatures, or none. In the latter case, the return value is just zero:

Var avg = averageTemperature(22.3, 25.4, 24, 26.2, 22.1) print(avg) Avg = averageTemperature() print(avg) // prints: // 0.0Copy the code

Note that mutable parameters can also exist with other normal parameters. For example, see the following function, which stores an athlete’s scores in various sports; It is also expected to provide the names of athletes:

struct Performance { var name: String var scores: [Double] } func keepPerformance(_ scores: Double... , name: String) -> Performance { Performance(name: name, scores: [scores]) }Copy the code

There are multiple variables

Prior to Swift 5.4, a function could contain only one variable argument. However, this has changed since version 5.4, and functions may have more than one such argument.

There is only one requirement to remember, which is obvious from the previous example; The next argument after a mutable argument should have a parameter label, so the compiler knows exactly which arguments are assigned to a mutable argument and which arguments are assigned to the next argument.

The following code demonstrates a function with three mutable arguments; Note that normal parameters can always be mixed in as well:

func showGameInfo(_ players: String... , points: Int... , fouls: Int...) { for i in 0.. <players.count { print(""" Player \(players[i]) scored \(i < points.count ? points[i] : 0) points and commited \(i < fouls.count ? fouls[i] : 0) fouls. """) } } showGameInfo("John", "Tom", "Max", "Ben", "Matt", points: 8, 4, 0, 4, fouls: 3, 2) // It prints: // Player John scored 8 points and commited 3 fouls. // Player Tom scored 4 points and commited 2 fouls. // Player Max scored 0 points and commited 0 fouls. // Player Ben scored 4 points and commited 0 fouls. // Player Matt scored 0 points  and commited 0 fouls.Copy the code

conclusion

Mutable parameters are a simple topic in Swift and a tool parameter worth considering. If you are implementing a function or method whose arguments can accept zero or more values, consider using mutable arguments; You end up with more readable and clearer code, and you retain the advantages of array handling. Anyway, I hope you found this article interesting; Thank you for reading!

  • Underlying related interview articles (github.com/iOS-Mayday/…
  • Resume guides and common algorithms (github.com/iOS-Mayday/…