Swift 60秒43 - Variadic functions

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift 60秒43 - Variadic functions相关的知识,希望对你有一定的参考价值。


0x00 Lesson

Some functions are ​​variadic​​​, which is a fancy way of saying they accept any number of parameters of the same type. The ​​print()​​​ function is actually ​​variadic​​: if you pass lots of parameters, they are all printed on one line with spaces between them:

print("Haters", "gonna", "hate")

You can make any parameter ​​variadic​​​ by writing ​​...​​​ after its type. So, an ​​Int​​​ parameter is a single integer, whereas ​​Int...​​ is zero or more integers - potentially hundreds.

Inside the function, Swift converts the values that were passed in to an ​​array​​ of integers, so you can loop over them as needed.

To try this out, let’s write a ​​square()​​ function that can square many numbers:

func square(numbers: Int...) 
for number in numbers
print("\\(number) squared is \\(number * number)")

Now we can run that with lots of numbers just by passing them in separated by commas:

square(numbers: 1, 2, 3, 4, 5)

0x01 我的小作品

欢迎体验我的作品之一:​​小汉字-XHanzi​​​ 汉字书写入门,常用汉字 3800 个,二级字表 2200 个
​App Store​​ 搜索即可~



以上是关于Swift 60秒43 - Variadic functions的主要内容,如果未能解决你的问题,请参考以下文章

Swift 60秒45 - Running throwing functions

来自 C++ 代码的预处理器指令 (_VARIADIC_MAX)

AFNetworking - 等待 60 秒后超时间隔与预期不同

JavaScript定时器案例:显示年月日时分秒+每隔60s发送一次短信

写了一个linux的计时脚本,能够输出时分秒

写了一个linux的计时脚本,能够输出时分秒