加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – Variadic参数和默认参数

发布时间:2020-12-14 04:43:27 所属栏目:百科 来源:网络整理
导读:我有这个功能: func sum(#startingValue:Int,additionalValue:Int = 77,values:Int...) - Int { var total:Int = startingValue + additionalValue for v in values { total += v } return total} 有没有什么方法可以调用它而不指定additionalValue参数的值
我有这个功能:

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)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读