简体   繁体   English

Swift 中的可选默认参数

[英]Optional Default Parameter in Swift

I have a function with default parameters in swift.我在swift中有一个带有默认参数的函数。

func test(string: String = "", middleString: String = "", endString: String = "") -> Void {
  // do stuff
}

I want to pass in variables that will be optional strings.我想传入将是可选字符串的变量。

let string: String? 
let middleString: String?
let endString: String?

How do I make it so that if the parameters are nil, use the default parameters.我如何做到这一点,如果参数为零,则使用默认参数。 If not, then use the values within the optionals.如果没有,则使用选项中的值。

test(string, middleString: middleString, endString: endString)

You'll have to use Optional strings String?你将不得不使用可选字符串String? as your argument type, with default values of nil .作为您的参数类型,默认值为nil Then, when you call your function, you can supply a string or leave that argument out.然后,当您调用您的函数时,您可以提供一个字符串或不使用该参数。

func test(string: String? = nil, middleString: String? = nil, endString: String? = nil) -> Void {
    let s = string ?? ""
    let mS = middleString ?? ""
    let eS = endString ?? ""
    // do stuff with s, mS, and eS, which are all guaranteed to be Strings
}

Inside your function, you'll have to check each argument for nil and replace with a default value there.在您的函数中,您必须检查每个参数是否为nil并替换为默认值。 Using the ??使用?? operator makes this easy.运算符使这变得容易。

You can then call your function by supplying all arguments, no arguments, or only the ones you want to include:然后,您可以通过提供所有参数、不提供参数或仅提供您想要包含的参数来调用您的函数:

test(string: "foo", middleString: "bar", endString: "baz")
test()
test(string: "hello", endString: "world")

尝试这个:

 test(string: string ?? "", middleString: middleString ?? "", endString: endString ?? "")

Note: Don't interpret this optional parameters as ?注意:不要将此可选参数解释为? , this is different approach. ,这是不同的方法。

Totally optional parameters, ie Don't even use while calling method.完全可选的参数,即在调用方法时甚至不要使用。

func doAddition(value1Name value1:Int = 0, value2Name value2:Int = 0, value3Name value3:Int = 0){
    print(value1+value2+value3)
}

Now all parameters are optional to add.现在所有参数都可以选择添加。 call how you like,随心所欲地呼唤,

doAddition(value1Name: 1)
doAddition(value1Name: 1, value2Name: 2)
doAddition(value3Name: 3)

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

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