简体   繁体   English

如何在不指定可选参数值的情况下迅速调用以下函数?

[英]How to call the following function in swift without specifying a value for the optional parameter?

In swift it is allowed to have parameters in functions with default values, and it is allowed to have parameters without external names. 快速允许在函数中使用带默认值的参数,并且允许不使用外部名称的参数。 But, what happens when I combine them? 但是,当我将它们结合在一起时会发生什么? For example, in the following code: 例如,在以下代码中:

func foo (a: Int, b: Int = 0, _ c: Int) {
    print(a + b + c)
}

Is there any way of call the function foo without specifying a value for parameter b ? 是否可以在不为参数b指定值的情况下调用函数foo方法?

No you can't. 不,你不能。 That's why Apple recommends in the Swift book to place parameters with default values at the end of the parameters list: 这就是Apple在Swift书中建议将带有默认值的参数放在参数列表末尾的原因: 摘自Swift书

You should have the default parameters at the end of the parameter list. 参数列表的末尾应具有默认参数。

func foo (a: Int, c: Int, b: Int = 0) {    //put your parameter with default value at the end
    print(a + b + c)
}
//you don't need to specifying a value for parameter b
foo(10, 11)  //21

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM