0

Assume I have a generic type like class Foo <T> with a method like func bar (_ arg: T).

If I do let foo = Foo<Void>(), I cannot do foo.bar() without getting:

Cannot invoke 'bar' with no arguments

Didn't this used to work in older versions of Swift? Or am I doing something wrong?

foo.bar(()) works, but is obviously less than ideal.

aleclarson
  • 18,087
  • 14
  • 64
  • 91
  • 3
    You could define a `func bar() { bar(()) }` overload in a `extension Foo where T == Void`, similar to [the example shown here](https://stackoverflow.com/a/46863180/2976878). – Hamish Feb 07 '18 at 16:22
  • I am not sure what is your question. The method has one argument of type `Void` and you have to specify it when invoking the method. What is your ideal? – Sulthan Feb 07 '18 at 16:29
  • @Hamish Your answer seems to be working. I'll accept it when you're ready. – aleclarson Feb 07 '18 at 16:29
  • 1
    @Sulthan `foo.bar()` is the ideal. `foo.bar(())` is 2 characters too many. It worked before in previous Swift versions. – aleclarson Feb 07 '18 at 16:30
  • @aleclarson I decided it would be best just to update my existing answer to note how it could be used to work with methods as well, so unless you have any objections, we can just close this as a dupe now. – Hamish Feb 07 '18 at 17:52
  • @Hamish Sure thing, go ahead. – aleclarson Feb 07 '18 at 17:54

1 Answers1

0

You can define the argument as optional and define nil as a default value to achieve this:

func bar (_ arg: T? = nil)
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223