NoodleOfDeath NoodleOfDeath - 7 months ago 20
Swift Question

Default parameters swift

For my default parameters should I write

func myFunc(optionA: Int? = 0)


or

func myFunc(optionA: Int! = 0)


Which is more advisable and/or more importantly which is used more in production? What happens if I use
Int!
instead of
Int?
? Can I still pass either an
Int
,
nil
, 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

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.