我有这个功能:
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 value func sum(#startingValue:Int,values:Int...) -> Int { return sum(startingValue: startingValue,values); } // Calling this will use whatever value you specified func sum(#startingValue:Int,#additionalValue:Int,additionalValue: additionalValue,values); } // The real function where you can set your default value func 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 value sum(startingValue:10,7) // = 115 // This way sets additionalValue to the value of 1 sum(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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。