[Swift] Variadic arguments

What is variadic argument?

An argument that can receive any number of values. It has the advantage of not making the caller of the function aware that it is an array.

How to use

Add ... after the argument definition. func function name (argument: type ...) {}

I wrote it

A function called print makes the argument a variable length argument. Put a, b, and c in the argument, and print as many as the number of arguments with the expression for in. You can also print it as an array in a function, like print ("first: \ (strings [0]) ").

func print(strings: String...) {
    if strings.count == 0 {
        return
    }
    print("first: \(strings[0])")  //first: a
    
    for string in strings {
        print("element: \(string)")
    }
}
print(strings: "a","b","c")  //element: a element: b element: c

References

Yosuke Ishikawa and Yasuyo Nishikawa, "[Supplementary Revised 3rd Edition] Introduction to Swift Practice: A Language with Intuitive Grammar and Safety", Gijutsu-Hyoronsha, April 28, 2020, p. 453

Recommended Posts

[Swift] Variadic arguments
Variadic arguments in various languages
Variadic argument
[Swift] Closure