Honey Honey - 2 months ago 6
Swift Question

How does type inference work with optionals?

I have a func like this:

func click(sender:UIButton?) {
//some code
}


and I want to call that func both like this:

- click() // ERROR: Missing argument for parameter #1 in call
- click(btn) // works
- click(nil) // works


I have read this question but I am still confused isn't an optional by default a
nil
isn't that what the whole idea of optionals is about? Why can't I just do
click()
?

FYI I do know that I can change the method signature to
func click(sender:UIButton? = nil)
and then
click()
would work but that somehow seems redundant and is like re-saying something that is already known to be the default

Answer

You are asking about two different things:

  • An optional type which is nil by default

    var button : UIButton?
    
  • An optional function parameter by passing a default nil value

    func click(sender:UIButton? = nil)