
func sum(#startingValue:Int,additionalValue:Int = 77,values:Int...) -> Int { var total:Int = startingValue + additionalValue for v in values { total += v } return total} 有没有什么方法可以调用它而不指定additionalValue参数的值?
我想要的是这样的:
sum(startingValue:10,1,2,3,4,5,6,7)解决方法 虽然这可能看起来像一个奇怪的工作,它确实有效,你可以使用方法重载:
// Calling this will result in using the default valuefunc sum(#startingValue:Int,values:Int...) -> Int { return sum(startingValue: startingValue,values);}// Calling this will use whatever value you specifIEdfunc sum(#startingValue:Int,#additionalValue:Int,additionalValue: additionalValue,values);}// The real function where you can set your default valuefunc sum(#startingValue:Int,values:Int[]) -> Int { var total:Int = startingValue + additionalValue for v in values { total += v } return total}// You can then call it either of these two ways:// This way uses will use the value 77 for additional valuesum(startingValue:10,7) // = 115// This way sets additionalValue to the value of 1sum(startingValue:10,additionalValue: 1,7) // = 38 说实话,我不完全确定为什么你的第一个解决方案不能自动工作,在我找到的文档中this:
If your function has one or more parameters with a default value,and
also has a variadic parameter,place the variadic parameter after all
the defaulted parameters at the very end of the List.
但无法使它工作,也许是一个错误?我猜它应该像我给你看的那样工作.如果指定additionalValue,它将使用它,否则它将使用默认值.也许它会在不久的将来自动运行(使这个解决方案无关紧要)?
原始答案
如果您只是想在调用函数时停止使用单词additionalValue,但下面的解决方案仍有效,但它仍然会为additionalValue指定一个参数(而不是OP正在寻找的内容).
在additionalValue前加一个下划线:
func sum(#startingValue:Int,_ additionalValue:Int = 77,values:Int...) -> Int { // ...} 然后你可以在没有警告的情况下调用它的方式:
sum(startingValue:10,7)
在这种情况下,additionalValue自动等于第二个参数,因此它将等于1
总结以上是内存溢出为你收集整理的swift – Variadic参数和默认参数全部内容,希望文章能够帮你解决swift – Variadic参数和默认参数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)