swiftfunctionoption-type

Default optional parameter in Swift function


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.

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()

Solution

  • Optionals and default parameters are two different things.

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

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

    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.

    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).