Swift - Take Nil as Argument in Generic Function with Optional Argument

Coder-256 picture Coder-256 · Mar 16, 2016 · Viewed 8k times · Source

I am trying to create a generic function that can take an optional argument. Here's what I have so far:

func somethingGeneric<T>(input: T?) {
    if (input != nil) {
        print(input!);
    }
}

somethingGeneric("Hello, World!") // Hello, World!
somethingGeneric(nil) // Errors!

It works with a String as shown, but not with nil. Using it with nil gives the following two errors:

error: cannot invoke 'somethingGeneric' with an argument list of type '(_?)'
note: expected an argument list of type '(T?)'

What am I doing wrong and how should I correctly declare/use this function? Also, I want to keep the usage of the function as simple as possible (I don't want do something like nil as String?).

Answer

Mike Pollard picture Mike Pollard · Mar 16, 2016

I guess the compiler can't figure out what T is just from nil.

The following works just fine though for example:

somethingGeneric(Optional<String>.None)