gpt4 book ai didi

swift - 可变参数和默认参数

转载 作者:搜寻专家 更新时间:2023-10-30 23:00:37 24 4
gpt4 key购买 nike

我有这个功能:

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, values:Int...) -> Int {
return sum(startingValue: startingValue, additionalValue: additionalValue, values);
}

// The real function where you can set your default value
func sum(#startingValue:Int, additionalValue:Int = 77, 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, 1, 2, 3, 4, 5, 6, 7) // = 115

// This way sets additionalValue to the value of 1
sum(startingValue:10, additionalValue: 1, 2, 3, 4, 5, 6, 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, 1, 2, 3, 4, 5, 6, 7)

在这种情况下,additionalValue 自动等于第二个参数,因此它将等于 1

关于swift - 可变参数和默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24124956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com