Swift函数中的默认可选参数 [英] Default optional parameter in Swift function

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

问题描述

当我将 firstThing 设置为默认值 nil 时,这可以工作,不需要默认值 nil 在调用函数时出现一个缺少参数的错误。

When I set firstThing to default nil this will work, without the default value of nil I get a error that there is a missing parameter when calling the function.

通过输入 Int?我认为它是可选的,默认值为 nil ,对吗?如果是这样,为什么没有 = nil

By typing Int? I thought it made it optional with a default value of nil, am I right? And if so, why doesn't it work without the = nil?

func test(firstThing: Int? = nil) {
    if firstThing != nil {
        print(firstThing!)
    }
    print("done")
}
test()


推荐答案

默认参数是两个不同的东西。

Optionals and default parameters are two different things.

可选是一个变量,可以是 nil ,就是这样。

An Optional is a variable that can be nil, that's it.

当您省略该参数时,默认参数使用默认值,该默认值如下所示: func test(param :Int = 0)

Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)

如果您指定一个可选的参数,则必须提供该参数,即使您想要的值传球是 nil 。如果你的函数看起来像这个 func test(param:Int?),你不能像这样调用它 test()。即使该参数是可选的,它也没有默认值。

If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.

您也可以将两者结合起来,并有一个可选参数,其中 nil 是默认值,如下所示: func test(param:Int?= nil)

You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).

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

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