Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why specializing a generic function explicitly is not allowed?

Tags:

swift

In Swift, one should use type of parameters or return value to implicitly specialize a generic function. The problem is, when I call function like this:

func serialize<T>(continuation: GenericWithLongName<T, NSError> -> Void) -> Void 

I cannot just write

serialize<SomeType> {
    obj in 
    ...
}

It should be

serialize {
    (obj: GenericWithLongName<SomeType, NSError>) -> Void in
    ...
}

which looks painful.

It seems this "feature" exists for a long time. Is it a design decision? Is there any negative implication from allowing explicitly specialization?

And is there any way to make code above neat and clean without refactoring that generic class?

like image 483
Liteye Avatar asked Mar 26 '16 05:03

Liteye


People also ask

What is the purpose of a generic function?

A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.

How do I call a generic function in Swift?

Solution. A generic function that you might need to use explicit specialization is the one that infer its type from return type—the workaround for this by adding a parameter of type T as a way to inject type explicitly. In other words, we make it infer from method's parameters instead.


1 Answers

One way to "specialize" the function is by including the generic type as a function parameter:

func serialize<T>(
    t: T.Type, 
    continuation: GenericWithLongName<T, NSError> -> Void ) -> Void { }

Now you can "specialize" the function like this:

serialize(SomeType.self) { 
    obj in 
    ... 
}

I don't know the answer to why your requested feature is not available. I agree that the feature you recommend would be useful, but in the meantime this works just as well and is almost as concise.

like image 104
Aaron Rasmussen Avatar answered Oct 20 '22 12:10

Aaron Rasmussen