Inferring type for a generic optional with a default value

I wrote a generic function

func f<T>(t: T? = nil, /* other parameters with default values */) {}

which worked fine until I realized that f cannot be called without a value for generic parameter because Generic parameter 'T' could not be inferred.

Changing to

func f<T>(t: T? = nil as String?, /* other ... */) {}

fixes the issue, that is calls such as f() compile, but that feels kind of ugly, for example any concrete type completely known to the compiler will do in the nil as String? part so how to choose the right one?

Is there a better way to do what I want, that is for the function to still be generic and allow calling without the T parameter when the default nil is acceptable?

Forgot to mention that I did consider having a non-generic overload such as

func f(/* other parameters */) {}

but it cannot defer to the generic version by calling f(t: nil, ...) because again, what is T?

You can’t have an unbound type variable.

It sounds like you want an existential type instead:

func f(t: Any? = nil)

The caller either supplies an existential storing a value of some concrete type, or nil.

I default to this, when needing the equivalent of "Optional with only the nil case", but it depends on what you're doing with .somes.

func f(t: (some Any)? = Never?.none) { }
// Error. "Switch must be exhaustive"
switch String?.none { case nil: break }

// Compiles.
switch Never?.none { case nil: break }