I was reading a few posts online about Swift variadic functions. I have to say, the amount of copying and pasting of content online is disturbing; Quite a few of the posts, some on Medium and some on various blogs, are almost identical in content as if the authors are just copying others work to get their name on published content. That sucks. Anyhow, on to my actual real authentic and uncopied post about Swift variadic functions…
A variadic function is a function that takes a variable number of parameters (or arguments if you prefer that term). In many of the examples described elsewhere, functions were created that did nothing more than process the data as an array of one type of data. And in that case, there were comments asking “why not pass in an array of data?” The question makes sense because why not pass in an array? Really, the code is not much different either way and I’d use an array in that case.
So what variadic function can’t be written to accept an array of data of the same type? The answer is a function that takes a variable number of variable type parameters. The String initializer that takes a format string and a variable number of variable type parameters is a good example of this. I’m sure there must be at least one other example in the Swift library code but I can’t think of what it is off the top of my head.
Here’s my test code that will someday become a function for creating an NSMutableAttributedString variable. It’s something I’ve been thinking about ever since I created my own String type to create and hold NSMutableAttributedString data:
This was just a test using a Swift playground in Xcode. I was testing the viability of passing in a format specified from an enum followed by a string. Some of my apps use formatted strings that are formatted with simple bold, italic, etc. features, and this would make the code much easier to write when strings like that are needed. Of course I threw in an extra format value just to see that everything worked as expected (although there was no expectation that this would not work). That might be a good way to combine format specifiers, something I didn’t really think of until I wrote this post.
I will update this post or write a new one if I ever get around to writing that function to create a formatted string like I mentioned earlier. Until then, this code seems like a good starting point for anyone else who need variable parameters of variable type or is searching for more info and keeps finding those boring integer averaging functions people write as an example.