NoodleOfDeath NoodleOfDeath - 1 year ago 106
Swift Question

Default parameters swift

For my default parameters should I write

func myFunc(optionA: Int? = 0)


func myFunc(optionA: Int! = 0)

Which is more advisable and/or more importantly which is used more in production? What happens if I use
instead of
? Can I still pass either an
, or no parameter whilst not having to unwrap the parameter when accessed? Is doing so considered lazy programming and may present potential memory insecurities?

Answer Source

0 Isn't nil. In either case, you're making optionA have a value of 0, not nil.

The correct answer here depends on what kind of interface you want your function to have.

  • If you want callers to be able to pass an Int, nil or no parameter at all, then optionA should be an Int? type.
  • If you want callers to be able to pass an Int, no parameter at all, but NOT nil, then optionA should be an Int type.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download