Swift中的可选默认参数 [英] Optional Default Parameter in Swift

查看:158
本文介绍了Swift中的可选默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在swift中有一个带默认参数的函数

I have a function with default parameters in 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)

推荐答案

你必须使用可选字符串字符串?作为你的参数类型,默认值为 nil 。然后,当你调用你的函数时,你可以提供一个字符串或保留该参数。

You'll have to use Optional strings String? as your argument type, with default values of 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
}

在你的函数中,你必须检查 nil 的每个参数,并用那里的默认值替换。使用 ?? 运算符可以轻松实现。

Inside your function, you'll have to check each argument for nil and replace with a default value there. 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")

这篇关于Swift中的可选默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆