Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?).

like image 741
Coder-256 Avatar asked Mar 16 '16 15:03

Coder-256


Video Answer


1 Answers

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)

like image 93
Mike Pollard Avatar answered Mar 17 '23 17:03

Mike Pollard