Default values for function parameters where value passed in is nil

4.6k views Asked by At

Is there a neat way to combine default function parameter values and optionals, so the parameter takes on the value of the supplied default when the parameter is specified in the function call, but it's value is nil?

For example:

class MyObj {

    var foobar:String

    init(foo: String?="hello") {
        self.foobar = foo!
    }
}

let myObj = MyObj() // standard use of default values - don't supply a value at all

println(myObj.foobar) // prints "hello" as expected when parameter value is not supplied

var jimbob: String? // defaults to nil

...

// supply a value, but it is nil
let myObj2 = MyObj(foo: jimbob) // <<< this crashes with EXC_BAD_INSTRUCTION due to forced unwrap of nil value

println(myObj2.foobar)

...or is the best bet to give the member constants/variables default values and then only change them if there is a value provided to the constructor, like this:

let foobar:String = "hello"

init(foo: String?) {
    if foo != nil {
       self.foobar = foo!
    }
}

Feels like there should be a neater solution, given other language features in this area.

1

There are 1 answers

1
Mike Pollard On BEST ANSWER

How about:

class MyObj {

    var foobar:String

    init(foo: String?=nil) {
        self.foobar = foo ?? "hello"
    }
}